如何不使用JS,用CSS :target实现导航栏标签选中高亮?
问题原因
你当前的代码逻辑有误:点击导航链接后,URL的哈希值对应下方的Section-*元素,而非导航栏里的h5,所以h5:target选择器永远无法匹配到目标元素,自然不会触发颜色变化。
解决方案
我们需要利用:target匹配被激活的Section元素,再通过属性选择器定位到导航中指向该Section的链接,实现高亮效果。同时调整HTML结构,让导航栏位于所有Section之后(因为CSS兄弟选择器~只能选择后续元素,而导航栏是fixed定位,视觉位置不受影响)。
修改后的完整代码
CSS
.Nav { display: inline-block; position: fixed; z-index: 100; background: black; width: 100%; top: 0; left: 0; text-align: center; } .Nav h5 { display: inline-block; position: relative; margin: 1rem; color: white; } .Nav a { display: block; width: 100%; text-align: center; font-size: 1rem; color: inherit; outline: 0 none; } #Section-1, #Section-2, #Section-3, #Section-4, #Section-5 { display: block; position: relative; padding: 70px; width: 100px; border: 2px solid red; } /* 当对应Section被激活时,高亮导航中指向它的链接 */ #Section-1:target ~ .Nav a[href="#Section-1"], #Section-2:target ~ .Nav a[href="#Section-2"], #Section-3:target ~ .Nav a[href="#Section-3"], #Section-4:target ~ .Nav a[href="#Section-4"], #Section-5:target ~ .Nav a[href="#Section-5"] { color: yellow; }
HTML
<div id="Section-1"> 11111111111 </div> <div id="Section-2"> 222222222222 </div> <div id="Section-3"> 33333333333 </div> <div id="Section-4"> 4444444444444 </div> <div id="Section-5"> 5555555555555555 </div> <div class="Nav"> <h5><a href="#Section-1">Section 1</a></h5> <h5><a href="#Section-2">Section 2</a></h5> <h5><a href="#Section-3">Section 3</a></h5> <h5><a href="#Section-4">Section 4</a></h5> <h5><a href="#Section-5">Section 5</a></h5> </div>
补充说明
- 导航栏使用
fixed定位,即使放在HTML结构的末尾,视觉上依然会固定在页面顶部,不影响正常布局和跳转体验。 - 当点击任意导航链接时,对应的Section会被
:target匹配,进而触发对应导航链接的黄色高亮,直到点击其他链接切换目标Section。
内容的提问来源于stack exchange,提问作者JohnBoo
相关产品推荐
相关产品推荐

