CSS Counters are like small variables managed entirely by CSS. They automatically increment and can be displayed using pseudo-elements like ::before and ::after. This makes them perfect for:
Chapter 1.2, 1.3.4, etc.section or chapter) that CSS can increase or reset.counter-reset – creates or resets a counter to a starting value.counter-increment – increases the value of a counter (default is +1).counter() – reads the current counter value and turns it into text.::before / ::after to visually show the number.A basic pattern for using CSS counters with a list is:
ol).li).::before or ::after to display the counter value.
/* Basic ordered list counter setup */
ol {
counter-reset: section;
}
li {
counter-increment: section;
}
li::before {
content: "Section " counter(section) ": ";
font-weight: 600;
}
With the CSS above applied, this HTML:
section.<li>."Section X: " before every list item.Rendered structure might look like:
Visually, each item will appear as: Section 1: Install the application, etc., without you needing to type “Section 1 / Section 2” manually.
These are the three key properties you use with counters:
| Property | Description | Example |
|---|---|---|
counter-reset |
Initializes or resets a counter. | counter-reset: section; |
counter-increment |
Increments the counter by 1 (or more). | counter-increment: section; |
content |
Displays the counter using ::before or ::after. |
content: "Step " counter(section); |
You can nest counters to create multi-level numbering like Chapter 1.1, Chapter 1.2, etc. A common pattern:
chapter counter on <body>.chapter on every <h2> (chapter title).section counter every time a new chapter starts.section on every <h3> (sub-section).
/* Set up a chapter counter for the whole page */
body {
counter-reset: chapter;
}
/* Each h2 is a chapter: increase chapter and reset section numbers */
h2 {
counter-increment: chapter;
counter-reset: section;
}
/* Show "Chapter 1. " before each h2 */
h2::before {
content: "Chapter " counter(chapter) ". ";
}
/* Each h3 is a section inside the current chapter */
h3 {
counter-increment: section;
}
/* Show "1.1 ", "1.2 " etc. before each h3 */
h3::before {
content: counter(chapter) "." counter(section) " ";
}
counter-reset: step 1 item;.h2 (chapters) and h3 (sub-sections) like in the example above.ol, li, and ::before with a step counter.Q1, Q2, Q3...) using a counter on heading elements.1.1.1) for chapter, section, and sub-section headings.