如何用 CSS 计数器为章节自动编号

用 counter-reset 设置起始值,用 counter-increment 递增,再在 ::before 的 content 中用 counter() 显示。示例中的章编号是 1 和 2,节编号是 1.1、1.2、2.1 和 2.2。

初始化、递增并显示计数器

在容器上用 counter-reset: chapter 0 初始化。每章通过 counter-increment: chapter 默认加 1,因此显示的第一个值是 1。counter() 读取该值。仅递增不会显示编号。 CSS Lists and Counters · Automatic Numbering

创建章与节编号的完整示例

保存为 css-counters.html 并打开。main 管理总的章计数器,每个 .chapter 从零开始创建 topic。节标题的伪元素用点连接当前的章和节编号。

<!doctype html>
<html lang="zh">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>用 CSS 为章和节编号</title>
  <style>
    body { margin: 20px; font: 16px/1.6 system-ui, sans-serif; color: #203348; }
    main { counter-reset: chapter 0; max-width: 650px; }
    .chapter { counter-increment: chapter; counter-reset: topic 0; }
    .chapter > h2::before { content: "第 " counter(chapter) " 章 "; color: #126f86; }
    .chapter h3 { counter-increment: topic; }
    .chapter h3::before { content: counter(chapter) "." counter(topic) " "; color: #126f86; }
  </style>
</head>
<body>
<main>
  <h1>CSS 学习提纲</h1>
  <section class="chapter">
    <h2>选择器</h2>
    <h3>类选择器</h3>
    <p>按 class 属性选取元素。</p>
    <h3>ID 选择器</h3>
    <p>按 id 属性选取元素。</p>
  </section>
  <section class="chapter">
    <h2>盒模型</h2>
    <h3>内边距</h3>
    <p>使用 padding 调整内容与边框之间的距离。</p>
    <h3>外边距</h3>
    <p>使用 margin 调整元素外部的空隙。</p>
  </section>
</main>
</body>
</html>

第二章的首节为 2.1,因为每章都会重新初始化节计数器。在第一章插入一个 h3,可以看到该章后续编号发生变化。第二章依然从 2.1 开始。

改变起始编号、步长和格式

将 counter-reset: chapter 4 用作初始值,首次加 1 后会显示 5 和 6。恢复为零,再用 counter-increment: chapter 2 查看 2 和 4。将步长恢复为 1 后,使用下面的规则可显示 I 和 II。 CSS Counter Styles · upper-roman

.chapter > h2::before {
  content: "第 " counter(chapter, upper-roman) " 章 ";
}

区分显示编号和文档结构

罗马数字改变的是显示格式。若节编号也需要这种格式,请给节规则中的 counter(chapter) 加上对应样式。重要标识应写入 HTML 或数据,有序列表应使用 <ol> 和 <li>。若主题已给标题编号,就不要在同一标题上再加计数器。 HTML Standard · ol