0

I'm trying to make an infinite background animation that slides from right to left. This what I achieved so far:

.container {
  height: 200px;
  width: 500px;
  font-size: 200px;
  font-family: sans-serif;
  font-weight: 600;
  background-image: url('https://i.ibb.co/5F5H2S2/background.jpg');
  background-size: cover;
  -webkit-animation: background-animation 5s linear infinite;
  animation: background-animation 5s linear infinite;
}

@keyframes background-animation {
  0% {
    background-position: 0 0;
  }
  100% {
    background-position: 100% 0;
  }
}
<div class="container">hello</div>

It works pretty well, the problem is that after 5 seconds, the background goes back at its initial position, and then start a new animation.

What I want is that the background continues sliding from right to left forever. I can somewhat achieve this by multiplying the values of the animation-duration and the background-position, for example:

.container {
  height: 200px;
  width: 500px;
  font-size: 200px;
  font-family: sans-serif;
  font-weight: 600;
  background-image: url('https://i.ibb.co/5F5H2S2/background.jpg');
  background-size: cover;
  -webkit-animation: background-animation 30s linear infinite;
  animation: background-animation 30s linear infinite;
}

@keyframes background-animation {
  0% {
    background-position: 0 0;
  }
  100% {
    background-position: 1000% 0;
  }
}
<div class="container">hello</div>

But this is not super elegant and just delays the problem. Is there any clever way to achieve this?

Temani Afif
  • 245,468
  • 26
  • 309
  • 415
Vald
  • 237
  • 2
  • 8

1 Answers1

2

Don't use cover, rely on percentage size

.container {
  height: 200px;
  width: 500px;
  font-size: 200px;
  font-family: sans-serif;
  font-weight: 600;
  background-image: url('https://i.ibb.co/5F5H2S2/background.jpg');
  background-size: 300% auto; /* 300% here */
  animation: background-animation 5s linear infinite;
}

@keyframes background-animation {
  0% {
    background-position: 0 50%;
  }
  100% {
    background-position: 150% 50%; /* 150 = 300/2*/
  }
}
<div class="container">hello</div>

Related: Using percentage values with background-position on a linear-gradient

Temani Afif
  • 245,468
  • 26
  • 309
  • 415