CSS 计数器
Pizza
Hamburger
Hotdogs
CSS 计数器是由 CSS 保持的“变量”,其值可以通过 CSS 规则递增(以跟踪其使用次数)。
计数器使您可以根据内容在文档中的位置来调整其外观。
带计数器的自动编号
CSS 计数器就像“变量”。变量值可以通过 CSS 规则递增(将跟踪它们的使用次数)。
如需使用 CSS 计数器,我们将使用以下属性:
counter-reset
- 创建或重置计数器counter-increment
- 递增计数器值content
- 插入生成的内容counter()
或counters()
函数 - 将计数器的值添加到元素
如需使用 CSS 计数器,必须首先使用 counter-reset
创建它。
下面的例子为页面(在 body 选择器中)创建一个计数器,然后为每个
元素增加计数器值,并在每个 元素的开头添加 "Section :":
ຄວາມຄົງຄວາມຕາມ
body {
counter-reset: section;
}
h2::before {
counter-increment: section;
content: "Section " counter(section) ": ";
}
ຄວາມຄົງຄວາມຕາມ
body { counter-reset: section; } h2::before { counter-increment: section; content: "Section " counter(section) ": "; }
嵌套计数器
下面的例子为页面(section)创建一个计数器,为每个
元素(subsection)创建一个计数器。
"section" 计数器为每个
元素计数,同时写入 "Section" 以及 section 计数器的值,"subsection" 计数器为每个 元素计数,同时写入 section 计数器的值以及 subsection 计数器的值:
ຄວາມຄົງຄວາມຕາມ
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) " ";
}
ຄວາມຄົງຄວາມຕາມ
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 Counter Attribute
Attribute | Description |
---|---|
content | Used with ::before and ::after pseudo-elements to insert generated content. |
counter-increment | Increment the value of one or more counters. |
counter-reset | Create or reset one or more counters. |