二维码

CSS 计数器

CSS 计数器

CSS 计数器是由 CSS 维护的“变量”,其值可以 由 CSS 规则递增(以跟踪它们的使用次数)。计数器 允许您根据内容在文档中的位置调整内容的外观。

使用计数器自动编号

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

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

  • counter-reset- 创建或重置计数器
  • counter-increment- 递增计数器值
  • content- 生成的插入物 内容
  • counter()or function - 添加 元素计数器的值counters()

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

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

1
2
3
4
body {  counter-reset: section;}  

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

嵌套计数器

以下示例为页面(部分)创建一个计数器,并为一个计数器 每个 <h1> 元素(小节)的计数器。“部分”计数器将是 对每个 <h1> 元素进行计数,其中“Section <value of the section counter>.“,并将计算”subsection“计数器 对于每个 <h2> 元素,其 “<节计数器的值>.<值 小节计数器>“:

1
2
3
4
5
6
7
8
9
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()

1
2
3
4
5
ol {  counter-reset: section;  
  list-style-type: none;}

li::before {  counter-increment: section;
  content: counters(section,".") " ";}

CSS 计数器属性

属性 说明
content 与 ::before 和 ::after 元素一起使用,以插入生成的内容
counter-increment 递增一个或多个计数器值
counter-reset 创建或重置一个或多个计数器
counter() 返回命名计数器的当前值