纯css实现中间展开下划线:用background+background-size控制,初始background-size:0 2px、background-position:center bottom,hover时过渡至100% 2px,配合inline-block和::after绝对定位确保精准居中与稳定动画。

用 background + background-size 控制下划线展开方向
纯 CSS 实现中间展开下划线,核心是把下划线做成一个背景色块,再通过控制它的宽度和位置来模拟“从中间向两边展开”。不能依赖 text-decoration,因为它不支持定位和动画缩放。
关键点:下划线必须是 background-image 或 background 渐变/色块,且初始宽度为 0,background-position 设为 center bottom,再配合 background-size 从 0 2px 动画到 100% 2px。
-
display: inline-block或inline-flex是必需的——否则background-position: center在内联元素上无效 - 必须显式设置
background-repeat: no-repeat,否则动画会错乱 - 推荐用
background: linear-gradient(#000, #000)而非纯色background-color,便于后续改粗细、颜色、圆角
完整可复用的 CSS 规则示例
以下代码直接可用,适配大多数链接或文字容器:
.hover-underline {
display: inline-block;
position: relative;
text-decoration: none;
color: inherit;
}
.hover-underline::after {
content: '';
position: absolute;
left: 0;
bottom: -2px;
width: 100%;
height: 2px;
background: currentColor;
background-size: 0 2px;
background-repeat: no-repeat;
background-position: center bottom;
transition: background-size 0.3s ease;
}
.hover-underline:hover::after {
background-size: 100% 2px;
}
注意:::after 必须用绝对定位并设 bottom 偏移,不能靠 line-height 或 padding 挤出来——那样在不同字体下容易错位。
为什么不用 transform: scaleX()?
常见误区是用 scaleX(0) → scaleX(1) 动画,但它默认以左上角为原点缩放,导致“从左往右”展开。想让它从中间展开,得加 transform-origin: center,但此时仍有两个隐患:
- 如果父容器有
overflow: hidden,缩放过程可能被裁剪 - 在部分 Safari 版本中,
transform-origin对伪元素支持不稳定,尤其嵌套在 flex 容器里时 -
scaleX本质是图形变换,对字体渲染可能引发 subpixel 模糊,而background-size是纯布局层操作,更稳定
兼容性与微调要点
这个方案在 Chrome 63+、Firefox 60+、Safari 12.1+、Edge 79+ 均表现一致。如需支持老版本 IE,只能降级为左右展开(改用 width + margin-left)。
实际使用时容易忽略的细节:
- 如果文字有
letter-spacing,background-position: center仍以盒模型中心为准,不是视觉字符中心——必要时改用left: 50%; transform: translateX(-50%)手动居中 - 下划线粗细建议统一用
height控制,别混用border-bottom和background,否则 hover 状态切换时会有 1px 跳变 - 移动端点击反馈弱,可加
@media (hover: hover)包裹 hover 规则,避免误触触发
中间展开看着简单,真正稳落地的关键不在动画写法,而在盒子模型的控制精度——尤其是 display 类型、伪元素定位方式、以及是否让 background 完全脱离文本流干扰。
前端入门到VUE实战笔记:立即使用
在学习笔记中,你将探索 前端 的入门与实战技巧!











