CSS导航菜单current类高亮被hover样式覆盖的问题求解
问题原因
- 选择器匹配错误:你在
<li>元素上添加了.current类,但原CSS中写的选择器#nav_menu li a.current是匹配带有.current类的标签,因此你的红色背景样式从头到尾未生效,当前页菜单项默认沿用了标签的白色背景。 - 样式优先级冲突:即使修正选择器后,普通标签的:hover样式优先级和.current下的样式优先级相同,且:hover样式写在后面,会覆盖.current的红色背景。
解决方案
修改对应CSS规则即可,调整后的完整可运行CSS如下:
#nav_menu { width: 100%; text-align: center; background-color: white; box-shadow: 5px 5px 20px 3px; border-bottom-left-radius: 6px; border-bottom-right-radius: 6px; } #nav_menu li{ display: inline-block; width:100px; background-color: white; color: white; height: 30px; line-height: 30px; margin: 0; } #nav_menu a{ display:block; text-decoration:none; background-color:#fff; color:black; height: 100%; } #nav_menu a:hover { opacity: 0.85; background-color:#009; color:#fff; } /* 修正选择器:匹配带current类的li下的a标签 */ #nav_menu li.current a { background-color: #BF0A30; color: #fff; } /* 额外设置当前页菜单项hover时仍保留红色,避免被普通hover覆盖 */ #nav_menu li.current a:hover { background-color: #BF0A30; opacity: 0.85; } ol,ul { list-style: none; margin: 0px; padding: 0px; }
如果不需要当前页hover时有透明效果,直接去掉.current a:hover规则里的opacity属性即可。
内容的提问来源于stack exchange,提问作者Christopher Rogers
相关产品推荐
相关产品推荐

