You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用::before和::after伪元素创建自适应文本宽度的下划线?

解决::after伪元素下划线宽度超出文本的问题

问题根源在于<h1>这类标题标签默认是块级元素,宽度会占满父容器的100%,而你给::after设置的width:100%继承了这个块级宽度,而非文本内容的宽度。下面是几种无需固定尺寸、让下划线自适应文本宽度的方案:

方案1:将标题转为行内块元素

给.c-title添加display: inline-block,让元素宽度由文本内容决定,这样::after的100%宽度就会匹配文本宽度:

* {
  box-sizing: border-box;
}

.c-title {
  position: relative;
  text-transform: uppercase;
  font-size: 1.2em;
  /* 添加这行 */
  display: inline-block;
}

.c-title::after {
  content: "";
  width: 100%;
  height: .2em;
  background-color: var(--c-title-underline-color);
  position: absolute;
  bottom: -2px;
  left: 0;
}

方案2:使用fit-content设置标题宽度

如果需要保持标题的块级特性(比如独占一行),可以用width: fit-content让块级元素的宽度收缩到文本内容的宽度:

* {
  box-sizing: border-box;
}

.c-title {
  position: relative;
  text-transform: uppercase;
  font-size: 1.2em;
  /* 添加这行 */
  width: fit-content;
}

.c-title::after {
  content: "";
  width: 100%;
  height: .2em;
  background-color: var(--c-title-underline-color);
  position: absolute;
  bottom: -2px;
  left: 0;
}

方案3:直接给伪元素设置fit-content宽度

如果不想修改标题元素的样式,也可以直接给::after设置width: fit-content,确保宽度匹配文本:

* {
  box-sizing: border-box;
}

.c-title {
  position: relative;
  text-transform: uppercase;
  font-size: 1.2em;
}

.c-title::after {
  content: "";
  /* 修改为fit-content */
  width: fit-content;
  height: .2em;
  background-color: var(--c-title-underline-color);
  position: absolute;
  bottom: -2px;
  left: 0;
  /* 确保空内容伪元素匹配文本宽度 */
  white-space: nowrap;
}

这几种方案都不需要设置固定尺寸,能自动适配文本内容的宽度。

内容的提问来源于stack exchange,提问作者JEmerson23

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 01:50:25