如何使用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
相关产品推荐
相关产品推荐

