You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

CSS中如何避免导航hover背景覆盖文本/超链接?

解决导航hover动画覆盖文本的问题

你遇到的核心问题是hover时的伪元素::after层级高于文本,导致文字被遮挡。只需做以下几个关键修改即可解决:

  1. 调整伪元素层级:给#nav-part2 h4::after添加z-index: -1,让动画层处于父元素的底层,不会覆盖上层的文本链接
  2. 修复链接的z-index错误:原代码中z-index: relative是无效语法,改为z-index: 1确保文本在动画层上方(配合伪元素的z-index:-1,这一步也可以省略,但写法更严谨)
  3. 修正hover文本颜色的选择器:原代码#nav-part2 h4:hover::a是错误的选择器写法,改为#nav-part2 h4:hover a才能正确触发hover时的文字颜色变化
  4. 修复代码里的其他小问题:比如全局选择器里的box-sizing: 0应为box-sizing: border-box,html的width: 100应为width: 100%,以及未闭合的<a>标签

修改后的完整代码如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
    font-family: inherit;
}

html, body {
    height: 100%;
    width: 100%;
}

#page1{
    height:100vh;
    width: 100%;
    background-color: #efeae3;
    position: relative;
}

nav{
    padding: 2vw 2vw;
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: space-between;
}

#nav-part2{
    display: flex;
    align-items: center;
    gap: 1vw;
}

#nav-part2 h4{
    padding: 10px 20px;
    border:  1px solid #8a8a8a89;
    border-radius: 50px;
    font-weight: 500;
    color: #000000bb;
    position: relative;
    font-size: 18px;
    transition: all ease 0.4s;
    overflow: hidden;
} 

#nav-part2 h4::after{
    content: "";
    position: absolute;
    height: 100%;
    width: 100%;
    background-color: gray;
    left: 0;
    bottom: -100%;
    border-radius: 50%;
    transition: all ease 0.4s;
    z-index: -1; /* 添加层级控制 */
}

#nav-part2 h4:hover::after{
    bottom: 0;
    border-radius: 0;
}

#nav-part2 h4 a{
    color: #000000bb;
    text-decoration: none;
    position: relative;
    z-index: 1; /* 修正z-index值 */
}

#nav-part2 h4:hover a{ /* 修正选择器写法 */
    color: white;
}
    </style>
</head>
<body>
    <div id="main">
        <div id="page1">
          <nav>
            <img src="https://assets-global.website-files.com/64d3dd9edfb41666c35b15b7/64d3dd9edfb41666c35b15c2_Sundown%20logo.svg" alt="">
            <div id="nav-part2">
                <h4><a href="#">Work</a></h4>
                <h4><a href="#">Studio</a></h4> <!-- 闭合a标签 -->
                <h4><a href="#">Contact</a></h4> <!-- 闭合a标签 -->
            </div>
          </nav>
        </div>
    </div>
    <script src="script.js"></script>
</body>
</html>

内容的提问来源于stack exchange,提问作者theslowtortoise

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 22:57:48