如何将带视差效果的分层英雄图部分区域隐藏在导航栏及其他元素后方?
解决视差英雄图仅显示在顶部区域的问题
我懂你遇到的困扰了——用fixed定位的视差图层因为脱离了文档流,父元素的overflow:hidden根本约束不了它,这也是为什么你调z-index没效果的核心原因。咱们来修改代码解决这个问题:
关键修改思路
fixed定位的元素是相对于浏览器视口的,所以会一直停留在页面可视区域,不受父元素的裁切限制。换成absolute定位后,图层会相对于设置了position:relative的父容器#hero定位,这样#hero的overflow:hidden就能生效,把超出容器的部分截断。
修改后的CSS代码
#hero { height: 1000px; overflow: hidden; position: relative; /* 确保hero在页面内容下方,导航栏在它上面 */ z-index: 1; } /* 调整图层定位方式 */ .layer { background-position: bottom center; background-size: auto; background-repeat: no-repeat; width: 100%; height: 800px; position: absolute; /* 从fixed改为absolute */ bottom: 0; /* 保持底部对齐的效果,和之前fixed的视觉一致 */ z-index: -1; } body, html { height: 100%; margin: 0; /* 给页面设置背景色,确保hero滚走后显示正确 */ background-color: #你的页面背景色; } /*Navbar styling */ #navbar { overflow: hidden; background-color: #130D0A; z-index: 9; text-align:center; /* 直接设置sticky定位,替代单独的.sticky类 */ position: sticky; top: 0; }
额外说明
- 把
#navbar的定位直接改成sticky,比单独加.sticky类更简洁,同时保持它的z-index:9,确保始终在#hero(z-index:1)上方。 - 给
body/html设置明确的背景色,这样当#hero滚出视口后,页面下方就会显示你想要的背景色,而不是图层内容。
这样修改后,你的视差图层就只会在#hero容器内部显示,滚动页面时,#hero离开视口后图层就会被截断,完美符合你的需求~
内容的提问来源于stack exchange,提问作者john f
相关产品推荐
相关产品推荐

