Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make background-image scroll continuously horizontally without a break in animation?

I'm trying to make a banner that scrolls sideways infinitely with css3 animation. The problem is that after the animation is over it has a harsh cut when it's restarting. I'm trying to figure out how to prevent that harsh animation.

I've put my code here.

@keyframes slideleft {
from{background-position: right;}
to {background-position: left;}
}

@-webkit-keyframes slideleft {
from{background-position: right;}
to {background-position: left;}
}

#masthead {
background-image: url('http://static.communitytable.parade.com/wp-content/uploads/2014/06/dogs-in-world-cup-jerseys-ftr.jpg');
animation: slideleft 5s infinite ease-in-out;
-webkit-animation: slideleft 5s infinite ease-in-out;
width: 100%;
height: 1200px;
}
<div id="masthead"></div>
like image 932
NinjaCoder Avatar asked Sep 04 '15 19:09

NinjaCoder


People also ask

What is the use of infinite scrolling background image?

The idea here is to create the appearance of a slideshow without the carousel. In other words, we're making a series of images the slide from left to right and repeat once the end of the images has been reached.

How do I keep my background fixed while scrolling CSS?

To keep your background fixed, scroll, or local in CSS, we have to use the background-attachment property. Background-attachment: This property is used in CSS to set a background image as fixed or scroll. The default value of this property is scroll.


1 Answers

JavaScript would probably be a better way to handle this. Though in CSS, you could repeat the background image and extend the background-position and animation duration to a very high number. Here is a fiddle.

@keyframes slideleft {
  from { background-position: 0%; }
  to { background-position: 90000%; }
}

#masthead {
  background-repeat: repeat-x;
  ...
  animation: slideleft 600s infinite linear;
}

If you are using jQuery it would be fairly straightforward:

(function animateBG() {
    $('#masthead').animate({
        backgroundPosition: '+=5'
    }, 12, animateBG);
})();

@keyframes slideleft {
  from { background-position: 0%; }
  to { background-position: 90000%; }
}

#masthead {
  background-image: url('https://i.stack.imgur.com/TE4UI.jpg');
  background-repeat: repeat-x;
  animation: slideleft 600s infinite linear;
  -webkit-animation: slideleft 600s infinite linear;
  width: 100%;
  height: 1200px;
}
<div id="masthead"></div>
like image 181
Will Avatar answered Oct 20 '22 04:10

Will