CSS rotate property – How to use the property in JavaScript

← PrevNext →

You can use CSS rotate property to rotate an element at a given angle. This is in addition to a CSS function called rotate() in transform property that also rotates an element. Here in this post I’ll show you how to use CSS rotate property dynamically inside a JavaScript code.

First, let’s see how the CSS rotate property “actually” works.

<!DOCTYPE html>
<html>
<head>
  <style>
    div { 
      padding: 10px; 
      width: 150px; 
      border: solid 1px red; 
      margin: 100px 0; 
      
      rotate: 90deg;
    }
  </style>
</head>

<body>
  <div>
    Content inside DIV element.
  </div>
</body>
</html>
Try it

It (the above CSS) turns or rotates the <div> element 90 degrees.

Unlike the transform property, the rotate property works independently.

Now, let’s do this dynamically. We’ll rotate the element from inside the JS code.

<!DOCTYPE html>
<html>
<head>
  <title>Rotate element using rotate property in JavaScript</title>
  <style>
    div { 
      padding: 10px; 
      width: 30%; 
      border: solid 5px red; 
      margin: 50px; 
    }
  </style>
</head>
<body>
  <div id='container'>
    Content inside DIV element.
    
    <p>
      Content inside P elememt.
    </p>
  </div>
</body>
<script>
  let rotate_el = () => {
    let ele = document.getElementById('container');
    ele.style.rotate = '90deg';	    // Using CSS "rotate" property.
  }

  rotate_el();
</script>
</html>
Try it

Rotate elements animatedly

You can use the rotate and transition property together inside your JS code to rotate elements animatedly.

Let us assume, I have a <div> element and a <p> element inside it. I can independently rotate each element.

<!DOCTYPE html>
<html>
<head>
  <style>
    div { 
      padding: 10px; 
      width: 30%; 
      border: solid 5px red; 
      margin: 50px; 
    }
    
    p { border: solid 1px green; padding: 3px; }
  </style>
</head>
<body>
  <div id='container'>
    Content inside DIV element.
    
    <p>
      Content inside P elememt.
    </p>
  </div>
</body>
<script>
    window.addEventListener('click', function (e) {
        if (e.target.tagName === 'DIV' || e.target.tagName === 'P') {
            e.target.style.rotate = '90deg'; 	    // rotate the element.
            e.target.style.transition = 'rotate 1s';  // animate using transition.
        }
    })
</script>
</html>
Try it

← PreviousNext →