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

如何使用CSS为静态链接设置无需hover即可展示的下划线效果

问题原因

你当前代码的核心错误是把原本属于:after伪元素的下划线属性,直接写在了.active-hover-underline-animation的根选择器上,而这个下划线效果本身是通过伪元素生成的,所以自然无法展示出预期的静态下划线效果。

调整方案

你可以直接复用原有悬浮样式的公共逻辑,不需要重复写冗余属性,修改后的CSS如下:

/* 原有基础样式不变 */
.hover-underline-animation {
    display: inline-block;
    position: relative;
    font-size: 22px;
    text-decoration: none;
    color: #333;
}

.hover-underline-animation:after {
    content: '';
    position: absolute;
    width: 100%;
    transform: scaleX(0);
    height: 2px;
    bottom: 0;
    left: 0;
    background-color: #0087ca;
    transform-origin: bottom right;
    transition: transform 0.25s ease-out;
}

.hover-underline-animation:hover:after {
    transform: scaleX(1);
    transform-origin: bottom left;
}

/* 新增/修改active类的样式 */
.active-hover-underline-animation {
    display: inline-block;
    position: relative;
    font-size: 22px;
    text-decoration: none;
    /* 文字颜色设为你需要的蓝色,和悬浮后保持一致 */
    color: #0087ca;
}
.active-hover-underline-animation:after {
    content: '';
    position: absolute;
    width: 100%;
    /* 直接设置scaleX为1,默认就展示全宽下划线 */
    transform: scaleX(1);
    height: 2px;
    bottom: 0;
    left: 0;
    background-color: #0087ca;
    /* 去掉transition属性就不会有动画效果 */
    transform-origin: bottom left;
}

如果想进一步精简代码,也可以给第二个a标签同时加hover-underline-animation和active-hover-underline-animation两个类,只需要写差异化的active样式即可:

/* 精简后的active类样式,其他原有样式不变 */
.active-hover-underline-animation {
    color: #0087ca;
}
.active-hover-underline-animation:after {
    transform: scaleX(1);
    transform-origin: bottom left;
    transition: none;
}

对应的HTML修改为:

<a class="hover-underline-animation active-hover-underline-animation" href="#">Why can't I get the same effect even if not hovered when static?</a>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 15:45:00