Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I change a background position with css3 animation?

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.

like image 569
fenerlitk Avatar asked Sep 01 '11 21:09

fenerlitk


People also ask

Can you animate background-position?

Your backgrounds can animate in any direction, up, down, left, right, or even diagonally. We will be using the CSS keyframes rule and the background-position property to create the effect.

Can you animate CSS background?

You can use a CSS background animation to help your site stand out from the crowd, emphasise your branding, or simply to look awesome. And because CSS has gotten so powerful, you can create some great-looking CSS background effects without needing a single line of JavaScript.

Which CSS property is used to change the position of the background image?

The background-position CSS property sets the initial position for each background image. The position is relative to the position layer set by background-origin .

How does CSS background-position work?

Definition and Usage. The background-position property sets the starting position of a background image. Tip: By default, a background-image is placed at the top-left corner of an element, and repeated both vertically and horizontally.


2 Answers

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.

like image 94
DuMaurier Avatar answered Nov 09 '22 04:11

DuMaurier


Some Code, looks like webkit only at this point in time.

.box {
    display:block;
    height:300px;
    width:300px;
    background:url('http://lorempixum.com/300/300') no-repeat;
    background-position:-300px;
    -webkit-transition:background-position 1s ease;
}

.box:hover{
    background-position:0px;
}

Via: http://jsfiddle.net/hfXSs/

More here: http://css-tricks.com/parallax-background-css3/

like image 23
Foxinni Avatar answered Nov 09 '22 05:11

Foxinni