为什么<li>标签制作的导航按钮hover悬停效果无法正常生效?
导航栏hover效果失效原因及修复方案
故障原因
- 核心原因:
h1元素使用了transform属性会创建新的层叠上下文,导致h1的层叠优先级高于后续的ul导航列表,实际h1元素覆盖了导航按钮区域,鼠标悬停时实际命中的是h1元素,无法触发li的hover效果。 - 次要问题1:
.topdiv中的float: top是无效CSS属性,无实际作用。 - 次要问题2:桌面端媒体查询
@media screen and (min-width: 992px)嵌套在平板端媒体查询内部,部分老旧浏览器对嵌套媒体查询支持不佳,也可能影响后续hover规则生效。 - 次要问题3:
a标签默认是行内元素,没有占满整个li容器,也可能导致部分区域悬停无响应。
修复方案
调整后CSS代码
@font-face { font-family: 'old'; src: url('/Fonts/OET.ttf'); } @media screen and (max-width: 600px) { /*Phones*/ } @media screen and (min-width: 600px) { /*Tablets*/ .topdiv { background-color: black; width: 100vw; margin-top: -3.5vw; margin-left: -8px; display: block; height: 10vw; } .home, .papers, .writers { width: 16.5vw; height: 8vw; background-color: white; border: none; font-size: 4vw; margin-left: 1vw; list-style-type: none; display: inline-block; border-radius: 5px; line-height: 7vw; text-align: center; } .home a, .papers a, .writers a { text-decoration: none; color: black; /* 让a标签占满整个li容器,扩大悬停/点击范围 */ display: block; width: 100%; height: 100%; } .home { background-color: rgb(192, 192, 192); } .home:hover, .papers:hover, .writers:hover { background-color: rgb(150, 150, 150); } } /* 把桌面端媒体查询移出嵌套结构,兼容老旧浏览器 */ @media screen and (min-width: 992px) { /*Desktops*/ }
调整后HTML代码
<div class="topdiv"> <h1 style="color: white;transform:translateX(1%) translateY(43%);font-size:5vw;font-family:old;">The EME Times</h1> <!-- 给ul添加相对定位和更高的层级,确保导航按钮在h1上方 --> <ul style="margin-top:-8.5vw;margin-left:35vw;position: relative;z-index: 10;"> <li class="home"><a href="#home">Home</a></li> <li class="papers"><a href="#papers">Papers</a></li> <li class="writers"><a href="#writers">Writers</a></li> </ul> </div>
内容的提问来源于stack exchange,提问作者Tyler Mazur
相关产品推荐
相关产品推荐

