CSS 的 border-bottom-width 不支持 transition 动画,因其不可插值;推荐用 transform: scaleX() 或 width 配合伪元素实现底部横线伸缩效果,优先选性能更好的 transform 方案。

input:focus 时 bottom-border 宽度过渡无效?
直接说结论:CSS 的 border-bottom-width 不支持 CSS 过渡(transition),哪怕你写了 transition: border-bottom-width 0.3s,浏览器也不会动。这是个常被忽略的底层限制 —— 浏览器只对可插值的属性做动画,而边框宽度在渲染层属于“离散重绘”,不是连续可插值的属性。
常见错误现象:border-bottom 在 focus 时突然变粗/变细,没有渐变效果;控制台没报错,但 transition 就是不生效。
- 别试图用
border-bottom-width做过渡,它天生不支持 - 真正能平滑过渡的是
width、transform: scaleX()、left/right配合overflow: hidden - 优先选
transform,性能最好(不触发重排)
用 transform: scaleX 实现底部横线伸缩
这是目前最推荐的做法:把横线抽成独立元素(比如 ::after),用 transform: scaleX(0) → scaleX(1) 控制伸缩,配合 transform-origin: left 确保从左向右展开。
使用场景:表单输入框、登录页、Material Design 风格 UI
立即学习“前端免费学习笔记(深入)”;
.input-with-line {
position: relative;
}
.input-with-line input {
padding-bottom: 8px;
border: none;
outline: none;
}
.input-with-line::after {
content: '';
position: absolute;
bottom: 0;
left: 0;
width: 100%;
height: 2px;
background: #2196F3;
transform: scaleX(0);
transform-origin: left;
transition: transform 0.25s cubic-bezier(0.25, 0.46, 0.45, 0.94);
}
.input-with-line input:focus + ::after {
transform: scaleX(1);
}
- 注意:伪元素必须和
input同级(所以常用label或额外div包裹,或用input:focus + ::after配合相邻兄弟选择器) -
cubic-bezier(0.25, 0.46, 0.45, 0.94)是 Material Design 推荐的缓动,比ease-in-out更自然 - 如果 input 是自闭合结构(如 Vue/React 中没兄弟元素),得用 wrapper 元素 +
:focus-within
:focus-within 在无兄弟结构下的兜底方案
当 input 没有紧邻的伪元素容器(比如用 <input> 单独存在,无法用 + ::after),就得靠父容器监听焦点状态。
兼容性:Chrome 61+、Firefox 64+、Safari 15.4+,基本可放心用(IE 不支持,需另配 JS)
.input-wrapper {
position: relative;
}
.input-wrapper::after {
content: '';
position: absolute;
bottom: 0;
left: 0;
width: 0;
height: 2px;
background: #2196F3;
transition: width 0.25s;
}
.input-wrapper:focus-within::after {
width: 100%;
}
-
:focus-within会响应子元素获得焦点,包括input、textarea、带tabindex的元素 - 用
width过渡比transform稍差一点(可能触发重排),但语义更直白,调试友好 - 若需支持老版本 Safari 或 Edge,得回退到 JS 监听
focus/blur并切换 class
为什么不用 border-bottom + opacity 或 color 过渡?
有人试过让 border-bottom 从透明变色、或从细变粗再加 opacity,看似“动了”,实则不符合需求 —— 用户要的是“横线从左向右延伸”的方向感,不是颜色淡入或粗细突变。
这种做法的问题很实际:
-
border-bottom-color过渡只能改变颜色,线还是整条瞬间出现 -
border-bottom-width过渡根本无效(前面已强调) - 用
box-shadow模拟下划线再过渡 width?会模糊、边缘发虚,且在高 DPI 屏幕上易出像素错位 - 真正需要“延伸感”时,只有
transform: scaleX或width+overflow: hidden能准确表达方向与起止
复杂点在于:你要决定是牺牲一点点兼容性换更顺滑的 transform,还是用 width 换可读性和兜底能力。多数项目现在直接选前者 —— 毕竟连 iOS 15.4 都支持 :focus-within 了。










