CSS counters are “variables” held by CSS, whose value can be incremented by CSS rules (to track their use). Counters allow you to adjust the appearance of content based on where it is in the document.
Automatic numbering with counter
CSS counters are like “variables”. Variable values can be incremented by CSS rules (which track their use).
To use CSS counters, we use the following properties:
counter-reset
– Creates or resets counterscounter-increment
– Increments the counter valuecontent
– Insert the generated contentcounter()
或counters()
Function – Adds the value of a counter to an element
To use a CSS counter, you must first create it using counter-reset.
The following example creates a counter for the page (in the body selector), then increses the counter value for each
element, and adds “Section
:” to the beginning of each < H2 > element:
:” to the beginning of each < H2 > element:
body {
counter-reset: section;
}
h2::before {
counter-increment: section;
content: "Section " counter(section) ":";
}
Copy the code
Nested counter
Subsection: The following example creates a counter for a page (section), and a counter for each
element (Subsection).
Subsection “counter counts each < H1 > element, writes both the values of “section” and the subsection counter, and the subsection counter counts each < H2 > element, Writes both the section counter value and the subsection counter value:
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) "";
}
Copy the code
Counters are also useful for creating overview lists because a new instance of a counter is automatically created in the child element. Here, we use the counters() function to insert a string between the different levels of nested counters:
ol {
counter-reset: section;
list-style-type: none;
}
li::before {
counter-increment: section;
content: counters(section,".") "";
}
Copy the code
CSS counter properties
attribute | describe |
---|---|
content |
with::before 和 ::after Pseudo-elements are used together to insert the generated content. |
counter-increment |
Increments one or more counter values. |
counter-reset |
Creates or resets one or more counters. |