页面body背景图被section背景色遮挡的问题求助
问题解决:Section背景色遮挡Body背景图
问题原因
section是body的直接子元素,你给每个section设置了height:100%和半透明背景色后,它们会完全覆盖在body的对应区域上。虽然背景色带透明度,但body的background-attachment: local会让背景图跟随body滚动,而每个section占据了视口全部高度,叠加后就把body的背景图彻底挡住了——只有当body自身设置背景色时,因为背景色会延伸到section下方,你才能看到背景图和背景色的叠加效果,但section的背景色始终在最上层。
解决方案
方案1:修改背景附着方式
把body的background-attachment: local改为fixed,让背景图固定在视口,不随页面滚动,这样section的半透明背景色就能透出下面的背景图:
body { background-image: url("https://montaigne-energie.fr/wp-content/uploads/2022/11/phare_blan3.svg"); background-position: 50% 2%; background-repeat: no-repeat; background-size: 140% auto; background-attachment: fixed; /* 修改此处 */ }
方案2:将背景图移到HTML元素上
把背景图设置在html标签上(html是body的父元素),body和section的半透明背景色就能自然透出底层的背景图:
html { height: 100%; margin: 0; background-image: url("https://montaigne-energie.fr/wp-content/uploads/2022/11/phare_blan3.svg"); background-position: 50% 2%; background-repeat: no-repeat; background-size: 140% auto; background-attachment: local; } body { height: 100%; margin: 0; background-color: transparent; /* 确保body背景透明 */ }
额外修复:HTML ID不匹配问题
你的HTML中最后第二个section的ID是sections5,但CSS里对应的选择器是#section5,这会导致该section无法应用背景色,需要统一ID:
<div class="section" id="section5"></div> <!-- 修正ID为section5 -->
内容的提问来源于stack exchange,提问作者Pierre
相关产品推荐
相关产品推荐

