You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

CSS如何设置多个依次排列不重复的背景图,实现9张不同背景展示

问题原因

你的代码存在两个核心错误导致只有第一张图循环显示:

  • 背景属性值数量不匹配:声明了9张背景图,但background-position给了10个坐标值,多余值会被浏览器忽略;且你设置的每张图间隔2796px远大于容器高度450px,除第一张图外其余默认都在容器可视区域外,动画匹配逻辑出错。
  • background-size仅设置100%,仅指定宽度,高度按原图比例自适应,没有显式控制每张图高度和排列位置的对应关系。

修正代码

CSS 代码

.overlay{
  position: relative;
  display: inline-block;
  margin-top:20px;
  /* 9张背景图顺序不变,先展示的图写在前面 */
  background: url(https://res2.yourwebsite.life/res/5eaf48a4da467d0022126577/6166b6eaeec90e00222e7f62_optimized_990), 
  url(https://res2.yourwebsite.life/res/5eaf48a4da467d0022126577/6166b6fb04d71200247e15fb_optimized_990), 
  url(https://res2.yourwebsite.life/res/5eaf48a4da467d0022126577/6166b6feec730a0022b756d4_optimized_990), 
  url(https://res2.yourwebsite.life/res/5eaf48a4da467d0022126577/6166b6ed7e627d0022f7acad_optimized_990), 
  url(https://res2.yourwebsite.life/res/5eaf48a4da467d0022126577/6166b6f020ea4d00234326ee_optimized_990), 
  url(https://res2.yourwebsite.life/res/5eaf48a4da467d0022126577/6166b6f7271d190023cb958e_optimized_990), 
  url(https://res2.yourwebsite.life/res/5eaf48a4da467d0022126577/6166b702271d190023cb95b6_optimized_990), 
  url(https://res2.yourwebsite.life/res/5eaf48a4da467d0022126577/6166b6f4eab9f000229958a9_optimized_990), 
  url(https://res2.yourwebsite.life/res/5eaf48a4da467d0022126577/6166b6e6fe83f10024675e66_optimized_990);

  background-repeat: no-repeat;
  /* 每张图宽度占满容器,高度和容器高度一致,刚好一屏显示一张 */
  background-size: 100% 100%;
  /* 9张图初始位置,每张依次向下偏移一个容器高度450px */
  background-position: 0 0, 0 450px, 0 900px, 0 1350px, 0 1800px, 0 2250px, 0 2700px, 0 3150px, 0 3600px;
  animation:100s scroll infinite linear;
  max-width: 50%;
  max-height: 90%;
  width:648px;
  height:450px;
  border: 3px solid #000;
}

@keyframes scroll{
  100%{
    /* 最终滚动距离为9张图总高度9*450=4050px,向上偏移刚好走完所有图 */
    background-position: 0 -4050px, 0 -3600px, 0 -3150px, 0 -2700px, 0 -2250px, 0 -1800px, 0 -1350px, 0 -900px, 0 -450px;
  }
}

HTML 代码

<div class="overlay"></div>

实现逻辑

多背景图的所有配套属性(background-position、background-size、background-repeat)的属性值数量要和背景图数量完全一致,浏览器会按顺序一一匹配。
上述代码让每张背景图的尺寸和容器尺寸完全一致,初始时第一张图在可视区,剩下的依次排在容器下方,每张偏移一个容器高度。动画滚动时所有图同步向上移动,每次移出一张的高度就刚好显示下一张,不会出现重复,9张全部走完后动画循环回到初始状态,实现无缝滚动效果。

内容的提问来源于stack exchange,提问作者faty fatoumata

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 04:39:02