stinkysGTI
stinkysGTI

Reputation: 611

CSS Animation - Move background position indefinitely

I'm trying to make an element's background move on a continuous loop from right to left without the snap back to the initial position and have it be smooth on all screen sizes. I've tried using repeat-x and doubling the image's width, and when it gets to the halfway point the animation loops, but you see it snap back to the first frame. So I came up with this hack (see below), but I'm hoping there's a better, more efficient way without having to use insane numbers and a smaller image.

Is there a way I can make the background repeat (repeat-x) but just move indefinitely?

Here's what I have at the moment:

.container:after {
    animation: mist 300s infinite linear;
    background: url("images/mist.webp") top left repeat-x;
    background-size: cover;
    content: "";
    height: 100%;
    left: 0;
    position: absolute;
    top: 0;
    width: 100%;
}

@keyframes mist {

    0% {
        background-position: 0 0;
    }

    100% {
        background-position: -20376px 0; /* image width x 6 */
    }

}

Upvotes: 0

Views: 1154

Answers (1)

Burham B. Soliman
Burham B. Soliman

Reputation: 1562

Actually you need to use background-repeat: round, and set the position -100vw, so it will repeat the bg for all the space, and will loop for view width only,

check this snippet

.container:after {

  animation: mist 6s infinite linear;
  background: url("https://global-uploads.webflow.com/5ef5480befd392489dacf544/5f9f5e5943de7e69a1339242_5f44a7398c0cdf460857e744_img-image.jpeg") top left;
  background-size: cover;
  background-repeat: round;
  content: "";
  height: 100%;
  left: 0;
  position: absolute;
  top: 0;
  width: 100%;
}

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

Upvotes: 1

Related Questions