最常见的原因是父容器未设高度或背景图路径错误;需确保元素有明确高度(如min-height:100vh),并检查控制台404错误。
最常见的原因是父容器没设置高度,或者图片路径错误导致背景根本没加载。浏览器默认把 background-attachment: fixed 应用于根元素(html)或设置了 height 的块级容器;如果父元素高度为 auto 且内容不够撑开,滚动区域实际在 body,而 body 默认不触发固定背景的渲染上下文。
min-height: 100vh)background-attachment: fixed 写在 html 或全屏 section 上,别只写在 div 里又忘了设高404 —— 背景图路径错时,样式看似生效,实则无图可“固定”纯 CSS 方案依赖 background-attachment: fixed,但它的“固定”是相对于视口,不是平滑视差。真视差需 JS 监听 scroll 动态改 background-position,或用 transform: translateY() 移动伪元素。
section.parallax {
height: 100vh;
overflow-x: hidden;
position: relative;
}
section.parallax::before {
content: '';
position: absolute;
top: 0; left: 0;
width: 100%; height: 200%;
background-image: url('bg.jpg');
background-size: cover;
background-position: center;
z-index: -1;
transform: translateY(0);
}
/* JS 中根据 scrollY 更新 */
document.addEventListener('scroll', () => {
const y = window.scrollY * 0.5; // 0.5 是视差系数
document.querySelector('section.parallax::before').style.transform = `translateY(${y}px)`;
});注意:上面代码中 querySelector 无法直接选中伪元素,真实项目要用 data-* 属性 + 真实子元素替代伪元素,或改用 requestAnimationFrame 避免卡顿。
scroll(默认值)让背景随元素内容一起滚动;local 让背景随**元素内部滚动条**滚动(比如 overflow: auto 的 div),适合长内容容器内局部背景跟随;fixed 则完全脱离文档流,固定在视口坐标系。
html { background-attachment: fixed }
background-attachment: local
local 在 Safari 旧版本有兼容问题,iOS 13.3 之前不支持iOS Safari 默认禁用 background-attachment: fixed(性能考虑),且很多安卓 WebView 也忽略它。这时不能依赖 CSS 固定背景,得换思路:
position: sticky + 全屏图片容器模拟固定背景navigator.userAgent,对 iOS 加 class 启用 JS 视差降级方案最稳妥的是:别强求“背景绝对固定”,优先保证内容可读、滚动流畅。所谓“动态背景滚动”,本质是用户感知的动效节奏,不是技术上非得锁死像素位置。