如何实现body背景固定,子元素滚动时背景保持静止?
问题原因
你给html和body都设置了height: 100%,这会把body的高度固定在当前视口高度。当内部div高度远超视口时,body并不会自动拉伸包裹内容,溢出的内容实际是在html的区域里显示。此时body的纹理背景只会覆盖初始视口大小的区域,滚动时自然会出现截断,加上background-attachment: fixed的特性,还会产生类似视差的错位效果。
修复方案
调整body的高度设置,让它既能覆盖视口,又能随内容自动扩展:
html, body { width: 100%; margin: 0; padding: 0; } html { height: 100%; /* 保持html高度为视口高度,让body的min-height能基于此计算 */ background: radial-gradient(#bcd197, #325757); background-repeat: no-repeat; background-size: cover; background-attachment: fixed; } body { outline: blue 3px dashed; min-height: 100%; /* 替换height:100%,让body高度至少为视口,内容溢出时自动拉伸 */ background-image: url("https://i.ibb.co/NFvCfrj/texture.png"); background-repeat: no-repeat; background-size: cover; background-position: center center; background-attachment: fixed; } div { outline: red 3px dashed; height: 200rem; width: 10rem; background-color: rgba(0,0,0,.5); margin: 1rem; }
额外说明
min-height: 100%会让body的高度默认等于视口高度,当内部内容超过视口时,body会自动向下拉伸,纹理背景也会跟着覆盖整个body区域。- 保留
background-attachment: fixed可以让渐变和纹理始终固定在视口,不会随滚动移动,完美实现你要的“背景静止、内容滚动”效果。
内容的提问来源于stack exchange,提问作者CuriousG
相关产品推荐
相关产品推荐

