How do I change a background position with css3 animation?

fenerlitk picture fenerlitk · Sep 1, 2011 · Viewed 24.3k times · Source

Lets say I have a div element, with a background in position: 0%; how would I change the position to e.g position: 100%; but with keyframes on hover

I can't seem to use keyframes properly, it never works and I have all the latest browsers.

Thanks.

Answer

DuMaurier picture DuMaurier · Sep 2, 2011

If you just want to animate background position on hover it's a lot easier to use a transition instead of keyframe animations. See this fiddle for an example: http://jsfiddle.net/hfXSs/

If you want to put in the extra effort of making it an animation you'll have to set the animation-play-state on the div to 'paused' and change it to 'running' on hover. See the spec on pausing animations here: http://dev.w3.org/csswg/css3-animations/#the-animation-play-state-property-

EDIT: I was bored so here's the same thing using keyframe animations: http://jsfiddle.net/wGRg5/

Obviously, the fiddle has the problem that when you aren't hovering over the div the animation pauses which is probably not the desired effect.