如何让两个重叠的粘性导航栏(sticky div)的所有元素均可显示且可点击?
如何让两个重叠的粘性导航栏(sticky div)的所有元素均可显示且可点击?
兄弟,我太懂你这种闹心的情况了——两个粘性导航栏叠在一块,本来想让两边的按钮都能正常点,结果后面的导航栏直接把前面的链接给盖死了,哪怕设了z-index也不管用。其实问题出在你没搞懂CSS里的堆叠上下文和z-index的生效规则,我给你捋清楚,再给你个简单的解决方案。
问题出在哪?
- z-index对非定位元素无效:你给
.topnav-right a设了z-index:2,但这些a标签是默认的position:static(浮动不改变元素的定位方式),所以这个z-index等于白写,完全不会生效。 - DOM顺序决定堆叠优先级:你的两个导航栏都是
position:sticky且top:0,后面的.topnav2-filter在DOM流里的顺序比.topnav靠后,哪怕.topnav设了z-index:0,后面的元素在堆叠层级上也会默认覆盖前面的——因为当堆叠层级相同时,DOM顺序靠后的元素会胜出。
推荐解决方案(改动小,效果直接)
我们可以把第一个导航栏的右侧链接改成独立的粘性元素,让它直接脱离第一个导航栏的堆叠上下文,这样不管两个导航栏怎么叠,链接都能牢牢待在最上层,同时第二个导航栏的按钮也能正常点击。
修改后的完整CSS代码:
body { font-family: 'Roboto Condensed', sans-serif; margin: 0; color: black; } /* 第一个全局粘性导航栏 */ .topnav { overflow: hidden; color: white; background-color: black; position: sticky; width: 100%; top: 0px; z-index: 0; /* 保持背景在最底层 */ } /* 调整右侧链接容器,变成独立粘性元素 */ .topnav-right { position: sticky; top: 0; z-index: 2; /* 确保链接在最上层 */ float: right; } .topnav-right a { color: white; padding: 1.3vh; text-decoration: none; position: relative; /* 让点击区域正常生效 */ } .topnav-right a:hover { color: gray; } .whitespace { width: 100vw; height: 100vh; } /* 第二个导航栏的容器 */ .topnav2-container { min-height: 100vh; min-width: 100vw; } /* 第二个粘性导航栏,调整z-index让它在背景和链接之间 */ .topnav2-filter { text-align: center; position: sticky; top: 0px; background-color: black; color: white; z-index: 1; } ul.topnav2-filter-links { list-style: none; padding: 0px; } ul.topnav2-filter-links > li { display: inline-block; margin: .5vh; } ul.topnav2-filter-links > li > a { display: block; padding: 8px 0; text-decoration: none; color: white; } ul.topnav2-filter-links > li > a:hover { color: gray; }
改动说明
- 独立的右侧链接:把
.topnav-right改成position:sticky,让它脱离第一个导航栏的堆叠上下文,自己成为一个独立的粘性元素,z-index:2确保它永远在最上层,不会被任何导航栏盖住。 - 调整导航栏层级:给
.topnav2-filter加z-index:1,让它在第一个导航栏的背景(z0)之上、右侧链接(z2)之下,这样中间的按钮既能正常显示,又不会被链接挡住点击。 - 修复z-index生效问题:给a标签加
position:relative,确保点击区域完全正常,不会出现“看得见点不着”的情况。
这样调整后,两个导航栏的元素就都能正常显示且可点击了,视觉上还是完整的黑色导航栏,完全符合你的需求~
内容来源于stack exchange
相关产品推荐
相关产品推荐

