Skip to main content

CSS Using Two Counters

Different levels of numbering can each have a counter of their own. Below, the page gets one counter (named "section"), and each <h1> element gets another (named "subsection").

Example

Prompt
Create a page with CSS counters that uses two counters: one named "section" reset on the body, and one named "subsection" reset on each h1. Use ::before pseudo-elements to prepend "Section X." before h1 headings and "X.Y" before h2 headings. Include several h1 and h2 elements to demonstrate the numbering.
Output: complete HTML page

The CSS counters() Function

Nested counters of the same name can be read in one go: the counters() function gives back their current values as a string.

That same function also lets you place a string between the different levels.

Example

Prompt
Create a page with nested ordered lists where list-style-type is set to none. Use a CSS counter named "section" that resets on each ol, increments on each li, and uses the counters() function with a "." separator in the li::before content to display nested numbering like "1", "1.1", "1.1.1".
Output: complete HTML page

CSS Counter Properties

These CSS properties and functions work with counters:

  • content - Inserts generated content, together with the ::before and ::after pseudo-elements.
  • counter-increment - Raises the value of one or more counters.
  • counter-reset - Creates one or more counters, or resets them.
  • counter() - Gives back the current value of the named counter.
  • counters() - Gives back the current values of named and nested counters.