【问题标题】:Text underline animation in CSS - the simplest way?CSS中的文本下划线动画 - 最简单的方法?
【发布时间】:2025-11-23 03:00:02
【问题描述】:

当用户指向我网站上的链接时,我会看到动画下划线效果。下划线比文本本身宽一点,因为有一点水平填充。

这是我想要达到的效果,我做到了:

我在考虑是否可以简化我的代码。经过反复试验,我在下划线元素上使用了负数margin-left,并在calc() 上将其width 计算为100% + 2 * padding。在我看来,它是一个过于复杂的解决方案。如果没有calc() 或者没有负边距也能达到同样的效果吗?

值得注意的是,添加包装元素不是选项。它必须是一个普通的 <a> 元素。

:root {
    --link-color: #f80;
    --link-underline-padding: .5em;
}

a {
    color: var(--link-color);
    display: inline-block;
    padding: 0 var(--link-underline-padding);
    text-decoration: none;
}

a:after {
    background-color: var(--link-color);
    content: '';
    display: block;
    height: .1em;
    margin-left: calc(var(--link-underline-padding) * -1);
    margin-top: .2em;
    transition: width .5s;
    width: 0;
}

a:hover:after {
    width: calc(100% + var(--link-underline-padding) * 2);
}
I find <a href="#">dogs</a> pretty cool.

【问题讨论】:

    标签: css css-animations css-transitions css-variables


    【解决方案1】:

    一个简单的背景动画就可以做到这一点:

    a {
      background: linear-gradient(currentColor 0 0) 
        bottom left/
        var(--underline-width, 0%) 0.1em
        no-repeat;
      color: #f80;
      display: inline-block;
      padding: 0 .5em 0.2em;
      text-decoration: none;
      transition: background-size 0.5s;
    }
    
    a:hover {
      --underline-width: 100%;
    }
    I find <a href="#">dogs</a> pretty cool.

    相关:

    How to animate underline from left to right?

    How to hover underline start from center instead of left?

    【讨论】:

    • 非常感谢,我喜欢现在这么简单!我对其进行了一些编辑以摆脱填充变量(因为填充现在仅在一个地方使用)并添加了--underline-thickness 变量(因为我们在正常和悬停状态下都使用它)。再次感谢
    • @RoboRobok 我做了另一个编辑以避免使用两次厚度;)(更新:颜色相同)
    • 天啊,我忘记了可以这样做,太棒了!现在删除--underline-thickness--link-color 怎么样?而且我不知道currentColor 存在:D
    • @RoboRobok 是的,您可以根据需要删除它们;)
    • 感谢您的编辑。我又更改了一件事——我将--s 重命名为--underline-width,以便更清楚地了解我们在那里所做的事情。我认为我们现在有了完美的 sn-p。
    【解决方案2】:

    如果您将a 设置为position: relative;,则可以使用position: absolute;left: 0px; 将其推过填充,然后只需使用width: 100% 使其延伸整个长度。

    :root {
        --link-color: #f80;
        --link-underline-padding: .5em;
    }
    
    a {
        position: relative;
        color: var(--link-color);
        display: inline-block;
        padding: 0px var(--link-underline-padding);
        text-decoration: none;
    }
    
    a:after {
        position: absolute;
        left: 0px;
        background-color: var(--link-color);
        content: '';
        display: block;
        height: .1em;
        margin-top: .2em;
        transition: width .5s;
        width: 0;
    }
    
    a:hover:after {
        width: 100%;
    }
    I find <a href="#">dogs</a> pretty cool.

    【讨论】:

    • 嘿,你的回答真的很棒!我希望你不介意我选择另一个,因为使用background-size 会让事情变得更容易。不过我也喜欢你的方法!
    • @RoboRobok,绝对是更好的答案,感谢您的考虑
    最近更新 更多