CSS Counters
CSS counters are “variables” that CSS maintains, and CSS rules can increase their values to see how frequently they are used. Using counters, you can change the way content looks depending on where it is in the document.
Automatic Numbering With Counters
Similar to “variables” are CSS counters. CSS rules have the ability to increment the values of the variables based on how frequently they are used.
The following properties will be utilized in order to operate with CSS counters:
- counter-reset – Creates or resets a counter
- counter-increment – Increments a counter value
- content – Inserts generated content
- counter() or counters() function – Adds the value of a counter to an element
A CSS counter must be generated with counter-reset before it may be used.
As an illustration, a counter for the page is created (in the body selector), and for each <h2> element, the counter value is increased. Additionally, “Section <value of the counter>:” is appended to the beginning of each <h2> element.
Example
body {
counter-reset: section;
}
h2::before {
counter-increment: section;
content: "Section " counter(section) ": ";
}
Nesting Counters
One counter is created for the page (part) and one counter is created for each <h1> element (subsection) in the example that follows. Each <h1> element with “Section <value of the section counter>.” will count the “section” counter, and each <h2> element with “<value of the section counter>.<value of the subsection counter>” will count the “subsection” counter:
Example
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) " ";
}
Because a counter is automatically established in child components, it can also be useful for creating outlined lists. Here, we insert a string between each level of the nested counters using the counters() function:
Example
ol {
counter-reset: section;
list-style-type: none;
}
li::before {
counter-increment: section;
content: counters(section,".") " ";
}
CSS Counter Properties
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 |