Restart CSS3 animations on hover without JavaScript

Spaceship animation restart

Back to the … how to restart CSS3 animations

For a project, I had to find a way to restart CSS3 animations when
hovering over it, but couldn’t use JavaScript.
At first I searched the net if something simple might show up.

But to no avail – everyone proposed you have to use JavaScript for that.
(By the way – if you found the “hack” following before, let me know ;).

So I studied the W3C’s opinion on the matter and found this sentence:

In order to restart an animation, it must be removed then reapplied.

Which made me think about how to remove an animation without JS.
And again, the W3C had the answer (if you bend your head around the original sentence ;) :

Note that since empty @keyframes rule are valid…

Read and Done, I started with assigning an empty animation on hover:

@keyframes emptyanim {}

#myDIVtoBeAnimated:hover {
    animation:emptyanim;
}

And surprise, surprise, it worked!
The next step was an easy one, why shouldn’t it work with no defined keyframe at all?

Done, tried, works – and even without browsers throwing CSS errors/warnings.

Finally see for yourself in this fiddle of it:

Have fun! :)

2 comments

This site uses Akismet to reduce spam. Learn how your comment data is processed.

  1. William · February 20, 2015

    I like it, but you have to hover over, then hover away for the animation to restart. I would love a way for the animation to restart by simply hovering over.

    • timhagn · February 20, 2015

      As the animation is “unset” on :hover, it only get’s reapplied afterwards. I sadly don’t know of a way without JS to achieve the behavior you describe : /.