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

链接下划线动画异常:鼠标悬停时所有链接均被下划线覆盖

导航链接下划线动画修复

我想给导航链接添加下划线动画,以下是我的HTML代码:

<header>
    <div class="title">
        <p>feldman</p>
    </div>
    <nav>
        <a href="intro.html">Intro</a>
        <a href="about.html">About</a>
        <a href="fieldman.html">Services</a>
        <a href="project.html">Project</a>
        <a href="contact.html">Contact</a>
    </nav>
</header>

初始CSS代码:

a::after{
    content: "";
    position: absolute;
    width: 0%;
    height: 1px;
    display: block;
    background-color: black;
    transition: width 0.2s ease-in-out;
}

a:hover:after{
 width: 100%;   
}

出现的问题:鼠标悬停任意链接时,所有链接都会被下划线覆盖。我需要让下划线仅作用于当前悬停的单个链接,以下是补充后的CSS代码:

nav a{
    color: black;
    text-decoration: none;
    margin: 6px;
    width: calc(100%/5);
    padding: 3px 4px 3px 5px ;
    line-height:1;
    position: relative;
    display: inline-block;
}

nav{
    margin-top: 9px;
    margin-right: 18px;
    width: 40%;
    height: 75%;
    display: flex;
    justify-content: center;
    margin: auto 10px;
}

header{
    display: flex;
    justify-content: flex-end;
}

问题原因与解决说明

初始代码里的伪元素a::after使用了绝对定位,但没有给<a>元素设置position: relative,导致伪元素的定位基准是最近的非静态定位父容器(比如nav),所以悬停时下划线会拉伸至父容器宽度,覆盖所有链接。

补充后的CSS给nav a添加了position: relative,让伪元素以当前<a>为定位基准,这样下划线就只会在当前悬停的链接下方从0%扩展到100%,不会影响其他链接。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 04:25:17