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

如何用HTML和CSS为标题添加底部边框?尝试后未达预期

解决标题底部边框/下划线的预期效果问题

你当前代码存在几个问题,导致无法达到预期效果:

  • margin-bottom: 30 缺少单位,需补充为 margin-bottom: 30px(或其他适配的单位)
  • 同时使用 border-bottom(撑满容器的通栏横线)和 text-decoration: underline(跟随文字长度的下划线),两者叠加会干扰最终显示效果

结合你想要的文字下方短横线效果,提供两种常用解决方案:

方案1:保留与文字宽度一致的下划线

去掉多余的border-bottom,调整下划线参数即可:

.widget-title {
  font-size: 1em;
  margin-bottom: 30px;
  text-decoration: underline;
  text-underline-offset: 0.5rem;
  text-decoration-thickness: 0.1875rem;
  text-decoration-color: green;
  color: black;
  /* 可选:若标题为块级元素,添加此属性让下划线仅跟随文字宽度 */
  display: inline-block;
}
<h1 class="widget-title"> Widget title </h1>

方案2:添加比文字短的居中底部横线

如果需要比文字宽度更短的居中横线,用伪元素实现更灵活:

.widget-title {
  font-size: 1em;
  margin-bottom: 30px;
  color: black;
  position: relative;
  padding-bottom: 0.5rem;
}

.widget-title::after {
  content: "";
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 60%; /* 可自定义横线宽度 */
  height: 0.1875rem;
  background-color: green;
}
<h1 class="widget-title"> Widget title </h1>

内容的提问来源于stack exchange,提问作者Khondokar Shamim Ahmed

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 06:45:36