如何实现流畅的垂直无限CSS背景图循环?
解决垂直无限滚动背景的卡顿与循环中断问题
你的核心问题出在背景图尺寸设置和动画衔接逻辑上,同时缺少性能优化导致卡顿:
background-size: cover会将背景图拉伸至容器满屏,让repeat-y失去作用,动画到bottom后没有重复的背景衔接,直接跳回顶部。- 动画的起始/结束位置未形成无缝循环,导致视觉中断。
- 未启用硬件加速,引发滚动卡顿。
修复后的完整代码
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>TEST</title> <style> body { margin: 0; padding: 0; } .background { background-image:url('https://i.pinimg.com/originals/a1/71/49/a17149990fa1bb216afa39e24901e90b.jpg'); background-repeat: repeat-y; background-position: center 0; /* 让背景图高度匹配容器,宽度自适应,保留repeat-y的重复效果 */ background-size: auto 100vh; /* 动画移动距离等于容器高度,实现无缝循环 */ animation: scroll 20s linear infinite; height: 100vh; width: 100%; position: fixed; top: 0; left: 0; z-index: -1; /* 启用硬件加速,解决卡顿 */ will-change: background-position; transform: translateZ(0); } .gradient { background: linear-gradient(to top, #000000b3 60%, rgba(0,0,0,0)); height: 100vh; width: 100%; position: fixed; top: 0; left: 0; z-index: 0; } .logo { /* 固定在顶部中央,避免页面滚动时移位 */ position: fixed; top: 20px; left: 50%; transform: translateX(-50%); z-index: 1; max-width: 50%; max-height: 50%; } @keyframes scroll { /* 从顶部0位置滚动到100vh位置,刚好让重复的背景衔接 */ from { background-position: center 0; } to { background-position: center 100vh; } } </style> </head> <body> <div class="background"></div> <div class="gradient"></div> <img src="https://www.citypng.com/public/uploads/small/116615720279wzwjyabcqvv4y6gzaozid8gaydhminycktgvrhn2mh5fqgvzropookgusxawpg1himbfjoeeneoaa9wt0clzsnjhk8vby4fxdur.png" alt="Logo" class="logo"> </body> </html>
关键修改说明
- 背景尺寸调整:将
background-size: cover改为auto 100vh,让背景图高度与容器一致,宽度自适应,确保repeat-y能生成上下重复的背景,为无缝循环提供基础。 - 动画逻辑优化:动画从
center 0滚动到center 100vh,移动距离等于容器高度,当动画结束时,重复的背景刚好衔接在当前视图下方,视觉上形成无限循环,不会跳回顶部。 - 性能优化:添加
will-change: background-position和transform: translateZ(0),开启浏览器硬件加速,解决滚动卡顿问题。 - Logo定位修正:将Logo改为
fixed定位,用top: 20px和transform: translateX(-50%)实现顶部居中,避免页面滚动时移位。
内容的提问来源于stack exchange,提问作者Birre
相关产品推荐
相关产品推荐

