HTML/CSS新手求助:鼠标悬停导航链接时Logo轻微偏移
问题:导航链接悬停时Logo出现轻微移动
我是HTML和CSS的新手,目前正在学习基础知识。当鼠标悬停在导航链接上时,页面中的Logo图片会出现轻微移动。我确定存在简单的解决办法,但暂时毫无头绪。
以下是我的CSS代码:
.header { min-height: 100vh; width: 100%; background-color: #14182d; } nav { display: flex; padding: 2% 6%; justify-content: space-between; align-items: center; } nav img { width: 70px; } .nav-links { flex: 1; text-align: left; margin-left: 160px; } .nav-links ul li { list-style: none; display: inline-block; margin: 40px 40px; position: relative; } .nav-links ul li a { color: #ffff; text-decoration: none; font-size: 20px; font-family: "SF UI Text Regular"; } .nav-links ul li::after { content: ""; width: 0%; height: 2px; background-color: #ffff; display: block; transition: 0.3s; float: right; margin-top: 4px; } .nav-links ul li:hover::after { width: 100%; float: left; }
解决办法
问题出在你给导航列表项的伪元素设置了float属性。当伪元素切换float: right和float: left时,会脱离正常文档流,导致父元素<li>的高度计算出现细微波动,进而影响整个nav容器的垂直对齐,最终带动Logo移动。
把float替换成外边距控制就能解决:
.header { min-height: 100vh; width: 100%; background-color: #14182d; } nav { display: flex; padding: 2% 6%; justify-content: space-between; align-items: center; } nav img { width: 70px; } .nav-links { flex: 1; text-align: left; margin-left: 160px; } .nav-links ul li { list-style: none; display: inline-block; margin: 40px 40px; position: relative; } .nav-links ul li a { color: #ffff; text-decoration: none; font-size: 20px; font-family: "SF UI Text Regular"; } .nav-links ul li::after { content: ""; width: 0%; height: 2px; background-color: #ffff; display: block; transition: 0.3s; margin-left: auto; /* 初始下划线居右 */ margin-top: 4px; } .nav-links ul li:hover::after { width: 100%; margin-left: 0; /* 悬停时下划线从左展开 */ }
修改说明:用margin-left: auto让下划线初始居右,悬停时改为margin-left: 0实现从左到右的扩展效果。这种方式不会让伪元素脱离文档流,父元素高度保持稳定,Logo也就不会再移动了。
内容的提问来源于stack exchange,提问作者Jørgen Klaastad
相关产品推荐
相关产品推荐

