如何用 CSS 在标题下方画短线

要在标题下画一条短线,可给 ::after 设置空的 content,把一个小块涂上背景色。标题文字保持原样,即使换行,最后一行下方也只有一条线。

在标题下画一条短线

把代码保存为 short-underline.html 并打开。空间足够时,两条线各长 48px。content: "" 生成空伪元素,display: block 让它独占一行。删除 content 或设为 none,确认短线消失后再还原。 CSS Pseudo-Elements · ::after

<!doctype html>
<html lang="zh">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>标题下的装饰短线</title>
  <style>
    body { margin: 20px; font: 16px/1.6 system-ui, sans-serif; color: #203348; }
    main { max-width: 600px; }
    .section-title { margin: 32px 0 16px; color: #146c87; font-size: 24px; }
    .section-title::after {
      content: "";
      display: block;
      inline-size: 48px;
      max-inline-size: 100%;
      block-size: 3px;
      margin-block-start: 12px;
      background-color: currentColor;
    }
    .center { text-align: center; }
    .center::after { margin-inline: auto; }
    .underlined { text-decoration: underline; text-underline-offset: 4px; }
  </style>
</head>
<body>
<main>
  <h1>短线与对齐</h1>
  <h2 class="section-title">左对齐的标题</h2>
  <p>装饰线从左侧开始,比标题更短。</p>
  <h2 class="section-title center">可换成两行的居中标题</h2>
  <p>用两侧的自动外边距让短线居中。</p>
  <p><span class="underlined">沿文字绘制的普通下划线</span></p>
</main>
</body>
</html>

调整线的长度和对齐方式

inline-size 设置长度,block-size 设置粗细,margin-block-start 设置间距。max-inline-size: 100% 可防止线溢出不足 48px 的标题盒。currentColor 使用标题的文字颜色。 CSS Color · currentColor

text-align: center 让文字居中。用 margin-inline: auto 让短线块单独居中。横排文字要对齐行尾,可在标题上用 text-align: end,再为线设置 margin-inline-start: auto 和 margin-inline-end: 0。只把 48px 改成 96px,对比后还原。

区分文字下划线和装饰线

要给文字加下划线,用 text-decoration: underline。border-bottom 沿标题盒边缘绘制,可能比文字长。想在整个标题下方放一条指定长度的线,则可用 ::after。 CSS Text Decoration · text-decoration-line

把有含义的标题和链接文字写进 HTML,装饰用的 content 保持为空。缩窄窗口可以看到短线仍在多行标题的下方。如果标题盒设置了固定高度,应检查换行是否裁掉短线。