要让CSS背景图固定不随页面滚动,关键在于使用background-attachment: fixed;该属性使背景图相对于视口固定,需配合background-size、position、repeat及足够高度(如100vh),并在移动端兼容性不足时可用伪元素+position:fixed替代。
要让CSS背景图固定不随页面滚动,关键在于使用 background-attachment: fixed。
该属性让背景图像相对于视口(viewport)固定,而不是随元素内容滚动。即使页面上下滚动,背景图仍保持在屏幕同一位置,产生视差效果。
background-image 的元素生效background-position 和 background-repeat 合理设置,否则可能显示不全或重复异常直接为容器添加固定背景:
.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 意外裁剪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 的限制,全平台支持更稳。