目录

CSS 计数器


比萨

汉堡包

热狗

CSS 计数器由 CSS 维护"variables",其值可以通过 CSS 规则递增(以跟踪它们的使用次数)。计数器可让您根据内容在文档中的位置来调整内容的外观。


使用计数器自动编号

CSS 计数器类似于"variables"。变量值可以通过 CSS 规则递增(这将跟踪它们的使用次数)。

为了使用 CSS 计数器,我们将使用以下属性:

  • counter-reset- 创建或重置计数器
  • counter-increment- 增加计数器值
  • content- 插入生成的内容
  • counter()或者counters()函数 - 将计数器的值添加到元素

要使用 CSS 计数器,必须首先使用以下命令创建它counter-reset

以下示例为页面(在正文选择器中)创建一个计数器,然后递增每个 <h2> 元素的计数器值并添加“Section <计数器的值>:" 到每个 <h2> 元素的开头:

示例

body {
  counter-reset: section;
}

h2::before {
  counter-increment: section;
  content: "Section " counter(section) ": ";
}
亲自试一试 »


嵌套计数器

以下示例为页面(部分)创建一个计数器,并为每个 <h1> 元素(子部分)创建一个计数器。 "section" 计数器将为每个带有“Section <节计数器的值>.", and the "subsection" counter will be counted for each <h2> element with "<节计数器的值>.<分段计数器的值>”:

示例

body {
  counter-reset: section;
}

h1 {
  counter-reset: subsection;
}

h1::before {
  counter-increment: section;
  content: "Section " counter(section) ". ";
}

h2::before {
  counter-increment: subsection;
  content: counter(section) "." counter(subsection) " ";
}
亲自试一试 »

计数器对于制作概述列表也很有用,因为会在子元素中自动创建计数器的新实例。这里我们使用counters()在不同级别的嵌套计数器之间插入字符串的函数:

示例

ol {
  counter-reset: section;
  list-style-type: none;
}

li::before {
  counter-increment: section;
  content: counters(section,".") " ";
}
亲自试一试 »

CSS 计数器属性

Property Description
content Used with the ::before and ::after pseudo-elements, to insert generated content
counter-increment Increments one or more counter values
counter-reset Creates or resets one or more counters
counter() Returns the current value of the named counter