视差网站开发问题:section标签文本需显示在图片上方
解决视差网站中文本被图片遮挡的问题
你遇到的问题是section内的文本被图片遮挡,核心原因是堆叠层级设置不当,以下是两种快速解决方法:
方法1:移除容器的负z-index
.container的z-index: -1会让整个容器(包括内部图片)处于底层,我们只需要让图片在容器内部处于底层即可,无需给容器本身设置负z-index。修改后的CSS代码如下:
* { margin: 0; padding: 0; box-sizing: border-box; } #wrapper { height: 100vh; overflow-x: hidden; overflow-y: auto; perspective: 10px; } .container { position: relative; height: 100%; display: flex; justify-content: center; align-items: center; transform-style: preserve-3d; /* 移除 z-index: -1 */ } .background, .foreground { position:absolute; height: 100%; width:100%; z-index: -1; /* 保留此设置,让图片在容器内部底层 */ object-fit: cover; } .background { transform: translateZ(-50px) scale(6); } .foreground { transform: translateZ(-30px) scale(4); } h1 { position:absolute; top: 5rem; left: 50%; transform: translateX(-50%); letter-spacing: 4px; font-size: 10rem; color: white; text-shadow: 0 0 10px rgba(0, 0, 0,0.3); } section { background-color: black; color: white; padding: 5rem 0; }
方法2:给section设置更高堆叠层级
如果需要保留.container的z-index: -1,可以给section添加定位和正z-index,强制让它显示在图片上方:
section { background-color: black; color: white; padding: 5rem 0; position: relative; z-index: 1; }
说明
- 方法1:移除容器的负z-index后,容器处于正常堆叠层级,内部图片通过自身的
z-index: -1留在容器底层,后续的section自然会显示在容器上方。 - 方法2:通过给section设置
position: relative和z-index: 1,提升其堆叠层级,覆盖在设置了负z-index的容器及图片上方。
内容的提问来源于stack exchange,提问作者Majji Mounisha
相关产品推荐
相关产品推荐

