::after伪元素画下划线比border-bottom更灵活,因其不撑开行高、可精准控制长度与位置;需设position:relative和content:"",用width:fit-content或max-content匹配文字宽度,避免错位。
::after 伪元素画下划线比 border-bottom 更灵活直接用 border-bottom 给标题加下划线,会撑开行高、影响垂直居中,还很难控制长度(比如只下划到文字末尾,不延伸到容器右边界)。::after 伪元素能精准定位、独立控制宽高颜色,且不参与文档流,是更干净的解法。
::after 下划线的基本结构和关键样式核心思路:给标题设 position: relative,再用 ::a 在其底部绝对定位画一条横线。必须显式设置
ftercontent: "",否则伪元素不渲染。
.title {
position: relative;
display: inline-block; /* 确保宽度包裹文字,避免下划线过长 */
}
.title::after {
content: "";
position: absolute;
left: 0;
bottom: -4px; /* 调整下划线离文字底部的距离 */
width: 100%;
height: 2px;
background-color: #333;
}display: inline-block 很关键——让 width: 100% 指向文字实际宽度,不是父容器宽度bottom: -4px 是常见起始值,具体数值需根据字体大小和行高微调border 或 box-shadow,纯靠 height + background-color 控制粗细和颜色默认 width: 100% 是对齐容器的,要“缩进”或“精确贴合”,得换策略:
width: fit-content(现代浏览器支持好,但 IE 完全不支持)left 和 right 同时设为 0,再配合 transform: scaleX(0.8) 缩放,或直接用 width: calc(100% - 16px) 手动减去左右留白width: max-content + margin: 0 auto 居中伪元素.title {
position: relative;
display: inline-block;
}
.title::after {
content: "";
position: absolute;
left: 0;
bottom: -4px;
width: max-content; /* 严格匹配文字宽度 */
height: 2px;
background-color: #333;
margin: 0 auto;
}当标题文字长度变化(如多语言切换、用户输入)、或字体在不同设备上渲染差异大时,下划线容易错位或截断:
max-content 在某些安卓 WebView 中表现不稳定,建议降级为 fit-content 或 JS 辅助计算宽度em 或 rem 设 bottom 值——字体度量(ascent/descent)因字体而异,用 px 更可控line-height > 1,bottom: -4px 可能不够,可改用 transform: translateY(2px) 微调transition 动画——部分浏览器在重排时会闪烁或跳动真正难的不是画出那根线,而是让它在各种字体、缩放、DPR、国际化文本下都稳稳贴在文字下方——这时候宁可多测几个真实设备,别信“理论上应该可以”。