CSS动画-无限移动背景位置

r3i60tvu  于 2023-01-14  发布在  其他
关注(0)|答案(1)|浏览(177)

我试图让一个元素的背景从右到左连续循环移动,而不会快速恢复到初始位置,并让它在所有屏幕尺寸上都很平滑。我尝试过使用repeat-x并将图像宽度加倍,当它到达中间点时,动画会循环,但你会看到它会快速恢复到第一帧。所以我想出了这个方法(见下文),但我希望有一个更好,更有效的方法,而不必使用疯狂的数字和一个较小的图像。
有没有一种方法可以使背景重复(repeat-x),但只是无限移动?
以下是我目前掌握的情况:

.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 */
    }

}
c86crjj0

c86crjj01#

实际上,您需要使用background-repeat:round,并设置位置-100vw,因此它将对所有空间重复bg,并仅对视图宽度循环,
检查此代码片段

.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>

相关问题