CSS 计数器

CSS 计数器是由 CSS 维护的变量,可以帮你自动生成章节的编号。

CSS 计数器是由 CSS 维护的变量,这些变量可能根据 CSS 规则增加已使用的次数。计数器让您可以根据内容在文档中的位置调整内容的外观。

使用计数器自动编号

要使用 CSS 计数器,设计以下属性和函数:

  • counter-reset - 创建或重置计数器
  • counter-increment - 增加计数器值
  • content - 插入生成的内容
  • counter()counters() 函数 - 返回当前计数器的值

要使用 CSS 计数器,必须首先使用 counter-reset 创建或重置计数器。

<h2> 标题自动生成章节编号:

<!DOCTYPE html>
<html>
  <head>
    <style>
      body {
        counter-reset: section;
      }
      h2::before {
        counter-increment: section;
        content: "第 " counter(section) " 章: ";
      }
    </style>
  </head>
  <body>
    <h1>CSS 计数器</h1>
    <h2>HTML 教程</h2>
    <h2>CSS 教程</h2>
    <h2>JavaScript 教程</h2>
  </body>
</html>

嵌套计数器

CSS 计数器还能生成多级计数器。

使用 CSS 计数器自动生成章节、小节编号:

<!DOCTYPE html>
<html>
  <head>
    <style>
      body {
        counter-reset: tutorial;
      }

      h1 {
        counter-reset: chapter;
      }

      h1::before {
        counter-increment: tutorial;
        content: "教程 " counter(tutorial) ". ";
      }

      h2::before {
        counter-increment: chapter;
        content: counter(tutorial) "." counter(chapter) " ";
      }
    </style>
  </head>
  <body>
    <h1>HTML 教程</h1>
    <h2>HTML 介绍</h2>
    <h2>HTML 元素</h2>

    <h1>CSS 教程</h1>
    <h2>CSS 介绍</h2>
    <h2>CSS 布局</h2>

    <h1>Javascript 教程</h1>
    <h2>JavaScript 介绍</h2>
    <h2>JavaScript 关键字</h2>
  </body>
</html>

计数器也可用于递归嵌套的情况:

<!DOCTYPE html>
<html>
  <head>
    <style>
      ol {
        counter-reset: section;
        list-style-type: none;
      }

      li::before {
        counter-increment: section;
        content: counters(section, ".") ". ";
      }
    </style>
  </head>
  <body>
    <ol>
      <li>item 1</li>
      <li>
        item 2
        <ol>
          <li>item 2-1</li>
          <li>item 2-2</li>
          <li>
            item 2-3
            <ol>
              <li>item 2-3-1</li>
              <li>item 2-3-2</li>
              <li>item 2-3-3</li>
            </ol>
          </li>
          <li>item 2-4</li>
        </ol>
      </li>
      <li>item 3</li>
      <li>item 4</li>
    </ol>

    <ol>
      <li>item 1</li>
      <li>item 2</li>
    </ol>
  </body>
</html>

CSS 计数器属性

属性 说明
content 使用 ::before::after 伪元素插入内容
counter-increment 增加计数器的值
counter-reset 创建或者重置一个计数器