视差滚动背景
视差滚动:多层背景以不同速度移动,产生立体纵深感。纯 CSS 用 background-attachment: fixed 让背景图相对视口固定,滚动时内容划过背景,形成最简易视差。
更完整的视差(多层不同速度系数)需要 JS 监听滚动改 transform;fixed 方案在移动端 Safari 兼容性差,做多端产品时建议降级。
- background-attachment: fixed = 零 JS 最简视差
- background-position 居中 + background-size: cover 保证铺满
- 移动端 fixed 兼容差:用 JS 改 transform 做多端方案
HTML
<style> .para { height: 240px; margin: 20px auto; border-radius: 14px; display: flex; align-items: center; justify-content: center; color: #fff; font-size: 26px; font-weight: 700; background: linear-gradient(rgba(0,0,0,.25), rgba(0,0,0,.45)), linear-gradient(135deg,#a371f7,#4a9eff 60%,#57ab5a); background-size: cover; background-position: center; background-attachment: fixed; } </style> <div class="para">滚动时背景“不动” = 视差</div> <div style="height:200px"></div> <div class="para">再经过一次视差区</div>
本节要点最简视差 = background-attachment: fixed;完整多层视差仍靠 JS 改 transform。




