利用 CSS 对标题进行自动编号

本页内容

当文章篇幅过长,对标题进行编号,可以给读者带来更好的阅读体验。本文将讲述如何利用 CSS 对标题进行自动编号。

实现

得益于 CSS 的计数器,我们可以很轻松地对标题进行计数。

介于文章篇幅和原理说明,只对 h2-h3 进行编号。你可以稍作修改,即可对 h2-h6 进行编号。

 1h1 {
 2  // 重置 h2 计数器
 3  counter-reset: h2Counter;
 4}
 5
 6@for $i from 2 through 3 {
 7  h#{$i} {
 8    // 增加当前标题的计数器
 9    counter-increment: h#{$i}Counter;
10    // 重置下个级别的计数器
11    counter-reset: h#{$i + 1}Counter;
12
13    // 于标题前显示编号
14    &::before {
15      display: inline;
16      @if $i == 2 {
17        content: counter(h2Counter) ".\0000a0";
18      } @else if $i == 3 {
19        content: counter(h2Counter) "." counter(h3Counter) ".\0000a0";
20      }
21    }
22  }
23}
  1. counter 获得计数器得值。
  2. counter-reset 重置计数器。
  3. counter-increment 增加计数器。

例子