CSS Counters: Automatic Numbering Without JavaScript
Deep in every browser sits a little integer variable system that almost nobody uses: CSS counters. They let you number list items, headings, steps, invoice lines, and definition terms entirely in the cascade â no JavaScript keeping a running total, no manually maintained 1. 2. 3. strings in the markup, no numbers that go stale the moment an editor reorders the content. The model is deliberately small: reset a named counter to a starting value, increment it as matching elements are encountered during rendering, and read it into content: on a pseudo-element. From that foundation come outline numbering with automatic renumbering, Roman and alphabetic formats, hierarchical 1.2.3 schemes, and decorative badges that track position in a flow you never hardcoded. The one caveat to internalize up front: counters are display-layer features. They produce text you can see, but they do not exist in the accessibility tree the way a real ordered list does.
The three properties, and the order they run in
counter-reset creates a counter and sets its initial value â the name is yours to choose, and the default starting value is 0, so the first increment lands on 1. counter-increment adds a step (default 1, or any integer, negative allowed) each time an element matching the selector is rendered. counter() inside a pseudo-element's content displays the current value. The sequence matters: reset on a container, increment on the repeated item, display on that same item's ::before. Nothing appears without content, and nothing increments without an explicit counter-increment on some rule:
.checklist {
counter-reset: task;
list-style: none;
padding: 0;
}
.checklist > li {
counter-increment: task;
position: relative;
padding: 0.6rem 0 0.6rem 2.5rem;
}
.checklist > li::before {
content: counter(task) ".";
position: absolute;
inset-inline-start: 0;
font-weight: 700;
color: #2563eb;
}
.invoice-lines {
counter-reset: line;
}
.invoice-line {
counter-increment: line;
}
.invoice-line::before {
content: "Item " counter(line) ": ";
font-weight: 600;
}
Counters are created in the scope of the element that resets them and all descendants, which is exactly why resetting on the container works: every ::before inside reads the same shared variable. Two elements cannot step on each other's totals as long as each reset lives on its own root â unless names collide within nested scopes, which is where the counters() function becomes relevant.
Numbering formats
The second argument to counter() selects the numeral system. The specification defines a long list of keywords, of which a practical subset covers nearly every design: decimal for standard numbers, upper-alpha and lower-alpha for A/a, upper-roman and lower-latin for Roman and European legal styles, decimal-leading-zero for 01, 02 style sequences (great for tabular alignment), and cjk-ideographic or hebrew only for genuinely multilingual contexts. CSS also accepts counters(name, separator) for nesting, plus explicit counter styles via @counter-style when you need ordinals like "1st, 2nd, 3rd" or custom icon sequences:
| Format keyword | 1 â 2 â 3 | Typical use |
|---|---|---|
| decimal | 1, 2, 3 | Steps, lists, invoices |
| decimal-leading-zero | 01, 02, 03 | Tabular indexes, sorted columns |
| upper-alpha | A, B, C | Quizzes, outlines |
| lower-alpha | a, b, c | Sub-questions, footnotes |
| upper-roman | I, II, III | Formal chapters, Super Bowl style labels |
| lower-roman | i, ii, iii | Sub-sections, preface numbering |
.chapter-outline {
counter-reset: section;
}
.chapter-outline h2 {
counter-increment: section;
}
.chapter-outline h2::before {
content: counter(section) ". ";
font-variant-numeric: tabular-nums;
}
.chapter-outline ol {
counter-reset: subsection;
list-style: none;
}
.chapter-outline ol li {
counter-increment: subsection;
}
.chapter-outline ol li::before {
content: counter(section) "." counter(subsection) " ";
color: #64748b;
margin-inline-end: 0.5rem;
}
Here the subsections compose two counters at read time â the current section value and the subsection value â producing 2.1, 2.2 without any glue logic. If a section advances, every subsection under it renumbers automatically because the display is computed at render, not stored.
Nested counters with counters()
Composing counter(a) "." counter(b) breaks down when nesting depth varies: three levels would need a.b.c with a hand-written pattern per depth. counters(name, separator) concatenates every instance of a counter in scope, joining each layer with the separator you supply. That is the mechanism behind legal outline numbering at arbitrary depth:
.legal {
counter-reset: clause;
}
.legal .clause {
counter-increment: clause;
}
.legal .clause .sub {
counter-reset: sub;
}
.legal .clause .sub > .item {
counter-increment: sub;
}
.legal .clause .sub > .item::before {
content: counters(clause, ".") " ";
font-weight: 600;
}
The subtlety that trips people: for counters() to capture each level, the counter must be incremented at every ancestor level too â nested counter-reset on sub-containers creates a fresh sub at each level, while the parent clause chain keeps stacking. Think of it as a stack of values where each incremented ancestor pushes a layer, and counters() reads the whole stack with your chosen glue.
Heading numbers and document-wide schemes
Numbering h2 and h3 across an article is a two-line pattern (reset, increment, prefix) and a genuine replacement for hand-typed "Section 4:" labels. The deeper win is consistency: editors inserting a section never break the sequence. For chapters that restart numbering per part, reset on the part element. For figures and tables numbered independently of headings â "Figure 3-2" meaning chapter 3, figure 2 â reset figure and table counters on each h2 scope and compose counter(chapter) with counter(figure) at read time.
A related but distinct feature is target-counter, available in paged media and increasingly in screen CSS, which lets a generated cross-reference read the counter value of a link's target â auto-updating "see page 12" style references. It pairs naturally with counters but requires the target to carry its own numbering.
Where counters are visual-only (and what to do about it)
Counters render text through content, and that generated text sits outside the DOM: it cannot be selected, copied, or reliably queried by find-in-page, and while modern screen readers do announce simple generated strings, the semantics are weaker than native elements. Numbering a div-based list with counters produces something that looks like a list but is not exposed as one. The honest guidance is twofold. First, when native semantics exist â ol, headings with aria-level â prefer them and let CSS counters decorate rather than replace. Second, when you do use counters for numbering (steps in a visual process, invoice lines, decorative indexes), verify with a screen reader that the numbers are announced usefully, and make sure the content remains understandable if they are not: the text should carry meaning on its own, with the number as reinforcement rather than the sole anchor.
Counter performance is a non-issue at realistic scale; incrementing integers during style resolution is cheap. The real maintenance concern is name hygiene: prefix counter names by feature (step, fig, inv-line) to avoid accidental collisions when components nest inside one another.
Restarts, countdowns, and unusual sequences
The default flow â one reset, forward increments, first item shows 1 â covers most jobs, but counters handle sequences that look like they need script. Counting down is an increment of a negative number: reset to your starting value and pass counter-increment: step -1 so each subsequent item subtracts. Jumping by more than one works the same way with counter-increment: step 5, which produces 5, 10, 15 for percentage scales or step labels. Restarting a sequence per section needs the reset scoped to the section element rather than the document, so every section begins from the same origin while totals stay independent â the invoice example earlier already does this by resetting on each list container.
Offsetting the first displayed value is a display-time decision, not an increment-time one: keep the increment honest and add arithmetic inside content, such as adding one in a calc expression when a sequence must start at 2 while the underlying counter starts at 0. Two counters can also be combined to show a total and a position at once â content: counter(item) " of " counter(total) â where total is incremented by a rule matching every item regardless of visibility, so the denominator reflects the whole collection even if CSS hides some entries. Since increments happen during rendering, anything that changes which elements match (a class toggle, a display change) reflows the numbering on the next paint. That is the feature working as designed: the sequence always describes what is currently rendered.
Common Mistakes
Nothing appears from a counter rule
Fix: Check all three parts exist: counter-reset somewhere in an ancestor, counter-increment on the item, and counter() inside the content of a pseudo-element
Numbers are off by one
Fix: Remember counters start at 0 with counter-reset, so the first increment displays 1 â reset to a negative value only if you deliberately want the first item to show 0
Nested outline numbering repeats the same number at every level
Fix: Use counters(name, separator) instead of counter(name), and increment at every ancestor level so each layer pushes onto the stack
Numbering is invisible to screen readers or cannot be copied
Fix: Prefer native ol and heading semantics where they exist; treat generated counters as decorative reinforcement rather than the only carrier of order
Best Practices
- Reset counters on the container that owns the numbering scope so each instance starts clean
- Prefix counter names by feature to prevent collisions when components nest
- Use font-variant-numeric: tabular-nums so multi-digit counter values align in tables
- Compose multiple counters for chapter-style numbering instead of hard-coding prefixes
- Keep the underlying content meaningful even if generated numbers are not announced
Interview Questions
Q1: Explain the roles of counter-reset, counter-increment, and counter().
counter-reset creates a named counter on an element and sets its starting value (0 by default), establishing a scope for descendants. counter-increment increases the value each time a matching element is rendered. counter() is a function usable inside content on a pseudo-element that displays the current value, optionally with a format keyword.
Q2: How do you produce hierarchical numbering like 1.2.3 at any depth?
Use counters(name, ".") which concatenates all active instances of the counter in the scope chain with the given separator. Ensure the counter is incremented at each ancestor level so every layer contributes, and use separate reset scopes for sub-levels when different sequences must restart.
Q3: Are CSS counters a good replacement for ordered lists?
Not as a semantics replacement. An ol exposes list structure and positions to assistive technology, supports value attributes, and its text is selectable. Counters are ideal for decoration and for numbering patterns with no native equivalent â headings, invoice lines, step badges â while keeping ol for real lists.
Key Takeaways
- Counters are scoped integer variables: reset on the container, increment per item, display via counter() in content
- Format keywords (decimal, upper-alpha, upper-roman, decimal-leading-zero) control numeral style with no markup changes
- counters(name, separator) builds arbitrary-depth hierarchical numbering from the scope stack
- Renumbering is automatic because values are computed at render time, so reordering content never breaks sequences
- Generated numbering is visual-first: keep native semantics where they exist and treat counters as decoration