JSFiddle - React, Tailwind, and code Playground

by rgthree

HTML

<div id="foo">This is a div in red. The blue box is a pseudo element of this div :before</div>

<button id="rotate">Rotate!</button>

CSS

#foo {
    width:100px;
    height:100px;
    position:relative;
    border:1px solid #F00;
}
#foo::before {
    content:'!';
    width:25px;
    height:25px;
    border:1px solid #00F;
    display:block;
    position:absolute; left:110%; top:50%; margin-top:-12px;
}

JavaScript

var btn = document.getElementById('rotate');

btn.addEventListener('click', function(){
    var rotation, sheet, cssText;
    
    // Randomly choose a rotation and create the cssText rule (webkit)
    rotation = Math.floor(Math.random() * (350 - 10 + 1)) + 10;
    cssText = '#foo::before {-webkit-transform:rotate('+rotation+'deg); }';
    
    // Since we're rotating a pseudo-element, we need to create a stylesheet
    // since :before's cannot be directly manipulated
    sheet = document.createElement('style');
    sheet.type = 'text/css';
    sheet.media = 'screen';
    if(sheet.styleSheet)
        sheet.styleSheet.cssText = cssText;
    else
        sheet.appendChild(document.createTextNode(cssText));
    document.head.appendChild(sheet);
});