应使用伪元素::after模拟下划线,通过width过渡实现从左向右滑入效果;父元素需设position: relative,伪元素用absolute定位并微调bottom值,避免布局干扰。

下划线在 hover 时“突然出现”,是因为默认的 text-decoration: underline 不支持 CSS 过渡(transition),直接显示/隐藏没有中间状态。想实现“从左向右滑入”的平滑下划线效果,不能依赖原生下划线,得用伪元素(如 ::after)模拟,并配合 width + transition 控制展开过程。
用伪元素画一条“可动”的下划线
核心思路:给文字加一个绝对定位的 ::after,初始宽度为 0,hover 时设为 100%,再用 transition 让宽度变化有动画。
示例代码:
a {
position: relative;
color: #333;
text-decoration: none;
}
a::after {
content: '';
position: absolute;
left: 0;
bottom: -2px;
width: 0;
height: 2px;
background-color: #007bff;
transition: width 0.3s ease;
}
a:hover::after {
width: 100%;
}
确保下划线对齐文字、不撑开布局
伪元素默认脱离文档流,但需注意几个细节:
立即学习“前端免费学习笔记(深入)”;
-
父元素必须设
position: relative,否则::after的left/bottom会相对整个页面定位 -
bottom 值要微调(如
-2px或-1px),避免和默认下划线位置冲突或离得太远 -
若文字有多行,此方法只适用于单行;多行需改用
background-image或box-shadow模拟,或借助line-height+clip-path
让下划线更自然:加延迟、控制起始点
如果希望下划线不是从最左开始,而是从文字中心或鼠标进入点出发,可以:
- 用
transform: scaleX(0)+origin控制缩放中心(比如transform-origin: left就是左起) - 或结合
transition-delay实现入场节奏差异 - 更进阶可用 JS 监听
mousemove动态计算起始位置,但纯 CSS 场景推荐保持left → width方案,简洁可靠
基本上就这些。关键是放弃原生 text-decoration,拥抱伪元素 + width + transition 组合。不复杂但容易忽略定位上下文和尺寸微调。










