NinjaCoder
NinjaCoder

Reputation: 125

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>

Upvotes: 9

Views: 7376

Answers (1)

Will
Will

Reputation: 20235

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.sstatic.net/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>

Upvotes: 10

Related Questions