You don't need any JavaScript or jQuery to achieve this effect; CSS3 Transitions and Transforms can do the trick for you.
To begin, ensure your div
has zero-degree rotation by setting the transform
attribute as follows:
div {
transform: rotate(0deg);
}
Next, create the hover-based transition (or spin effect) using the :hover
pseudo-element like this:
div:hover {
transition: transform 1s ease;
transform: rotate(360deg);
}
If you want the element to return to its original position with a transition, simply add the transition attribute to the CSS for div
:
div {
transform: rotate(0deg);
transition: transform 1s ease;
}
Feel free to adjust the timing value (1s
) to suit your preference, even down to milliseconds.
More information on CSS3 Transitions and Transforms can be found here:
See a live example of this rotation effect in action here: http://www.w3schools.com/css/tryit.asp?filename=trycss3_transition2.
This feature is supported by approximately 76% of web browsers. Check compatibility here: http://caniuse.com/#search=transitions
Note that some browsers may require vendor prefixes to support the transition
property. For instance, Chrome and Safari use -webkit-
, so you should include this prefix like so:
-webkit-transition: transform 1s ease;
. See the list of vendor prefixes below:
- Chrome/Safari:
-webkit-
- Opera:
-o-
- Firefox:
-moz-
- Internet Explorer:
-ms-