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>
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>
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>