使用计数器自动编号
CSS 计数器使用到以下几个属性:
counter-reset
- 创建或者重置计数器counter-increment
- 递增变量content
- 插入生成的内容counter()
或counters()
函数 - 将计数器的值添加到元素
要使用 CSS 计数器,得先用 counter-reset 创建:
body {
counter-reset: section;
}
h2::before {
counter-increment: section;
content: "Section " counter(section) ": ";
}
嵌套计数器
以下实例在页面创建一个计数器,在每一个 <h1> 元素前添加计数值 "Section <主标题计数值>.", 嵌套的计数值则放在 <h2> 元素的前面,内容为 "<主标题计数值>.<副标题计数值>":
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,".") " ";
}