Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Animate background image's position back and forth

I'd like to animate my background image and repeat on x from left to right and right to left when the position is on the end.

My code :

@keyframes animatedBackground {
  0% { background-position: 0 0; }
  100% { background-position: -100% 0; }
}

body.rotonde{
  background-image: url(../pages/bg.jpg);
  background-repeat: repeat-x;
  animation: animatedBackground 15s linear infinite;
  overflow: hidden;
}

My code doesn't work because when the background is on -100%, I get a restart on 0.

like image 828
tonymx227 Avatar asked Mar 12 '23 01:03

tonymx227


2 Answers

The reason why you get a restart on 0 as soon as it reaches -100% is because of how animations work in general. Once they complete a loop, they generally go back to their original state and restart the next loop. So, as soon as it reaches -100% (the end state), it resets the position to 0 (the start state).

from left to right and right to left when the position is on the end

For the above, you can use the animation-direction as alternate. This would make the animation animate the background position from 0 to -100% for odd numbered iterations and then from -100% to 0 for even numbered iterations.

@keyframes animatedBackground {
  0% { background-position: 0 0; }
  100% { background-position: -100% 0; }
}

body{
  background-image: url(http://placehold.it/100x100);
  background-repeat: repeat-x;
  animation: animatedBackground 15s linear alternate infinite;
  overflow: hidden;
}

Note: In the above snippet, it goes from right to left in the odd iterations and left to right in even ones. If you need it the other way around, just reverse the keyframes. My intent was just to give a demo of the alternating motion.

like image 182
Harry Avatar answered Mar 24 '23 10:03

Harry


Try this

 @keyframes animatedBackground {
        from { background-position: 0 0; }
        to { background-position: 100% 0; }
    }


    #animate-area   { 
        width: 560px; 
        height: 400px; 
        background-image: url(../pages/bg.jpg);
        background-position: 0px 0px;
        background-repeat: repeat-x;

        animation: animatedBackground 40s linear infinite;
    }
like image 42
Wasiq Muhammad Avatar answered Mar 24 '23 12:03

Wasiq Muhammad