EdwardBlack EdwardBlack - 1 month ago 13
CSS Question

How to animate transform: rotate(Xdeg);

Is it possible to animate

transform: rotate(Xdeg);
?

e.g. I have a
div
with id "awesomeDiv" and try to animate the rotation on hover.

It should animate from
-24deg
to
0deg
on hover and back from
0deg
to
-24deg
again if the mouse goes out.

I've tried it like this:



$("#awesomeDiv").hover(
function()
{
$(this).animate({
transform : "rotate(0deg)"
});
},
function()
{
$(this).animate({
transform: "rotate(-24deg)"
});
}
);

div#awesomeDiv {
position: absolute;
background-color: #D8D8D8;
width: 200px;
height: 200px;
transform: rotate(-24deg);

margin-left:30px;
margin-top: 30px;
background-image: url("http://ih0.redbubble.net/image.218467778.5415/fc,220x200,white.u2.jpg");
}

div#centerMe {
position: relative;
margin-top: 92px;
color: white;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="awesomeDiv">
<div id="centerMe">
<center>Im Aw<span style="color:black">es</span>ome!</center>
</div>
</div>




Answer

You can do this with simple CSS transitions itself like in the below snippet. Just set the transition property on the div#awesomeDiv and then add the transform: rotate(0deg) to the :hover state.

In the transition property, you can also specify the duration over which the movement should take place, the timing function (like ease, ease-in, ease-out etc) and any delays. For more details about the transition property, you can refer to the SO Documentation on Transitions.

div#awesomeDiv {
   position: absolute;
   background-color: #D8D8D8;
   width: 200px;
   height: 200px;
   transform: rotate(-24deg);
  
   margin-left:30px;
   margin-top: 30px;
   background-image: url("http://ih0.redbubble.net/image.218467778.5415/fc,220x200,white.u2.jpg");
  transition: transform 1s ease;
}

div#centerMe {
   position: relative;
   margin-top: 92px;
   color: white;
}
div#awesomeDiv:hover{
  transform: rotate(0deg);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="awesomeDiv">
  <div id="centerMe">
     <center>Im Awesome!</center>
  </div>
</div>