要让CSS背景图固定不随页面滚动,关键在于使用background-attachment: fixed;该属性使背景图相对于视口固定,需配合background-size、position、repeat及足够高度(如100vh),并在移动端兼容性不足时可用伪元素+position:fixed替代。

要让CSS背景图固定不随页面滚动,关键在于使用 background-attachment: fixed。
background-attachment: fixed 的作用
该属性让背景图像相对于视口(viewport)固定,而不是随元素内容滚动。即使页面上下滚动,背景图仍保持在屏幕同一位置,产生视差效果。
- 仅对设置了明确
background-image的元素生效 - 需配合
background-position和background-repeat合理设置,否则可能显示不全或重复异常 - 在移动端 Safari 中部分版本存在兼容性问题,可能被忽略或表现异常
基础写法示例
直接为容器添加固定背景:
.hero {
background-image: url('bg.jpg');
background-size: cover;
background-position: center;
background-repeat: no-repeat;
background-attachment: fixed;
height: 100vh;
}
注意:必须设置足够高度(如 height: 100vh),否则因内容少导致容器不够高,固定效果不可见。
立即学习“前端免费学习笔记(深入)”;
常见问题与应对
实际使用中容易遇到以下情况:
-
背景不动但内容遮挡:确保背景容器没有被其他元素的
z-index或overflow: hidden意外裁剪 -
移动端失效:iOS Safari 默认禁用
fixed背景以提升性能;可改用background-attachment: scroll+ JS 模拟,或用伪元素 +position: fixed替代 -
文字看不清:叠加半透明遮罩层(
::before伪元素 +rgba(0,0,0,0.4))提升可读性
替代方案(更稳定)
若需兼顾兼容性与效果,推荐用定位伪元素模拟:
.hero {
position: relative;
height: 100vh;
}
.hero::before {
content: '';
position: fixed;
top: 0; left: 0;
width: 100%; height: 100%;
background: url('bg.jpg') center/cover no-repeat;
z-index: -1;
}
这种方式绕过 background-attachment 的限制,全平台支持更稳。










