1 min read

CSS Counters

CSS counters are basically "variables" maintained by CSS whose values can be incremented by CSS rules (to track how many times they are used). Counters let you adjust the appearance of content based on its placement in the document.

1. The Concept

Counters are useful for creating numbered lists, section numbering (1.1, 1.2, 2.1), or counting elements without using <ol>.

2. Properties

  • 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.

3. Basic Usage

To use a CSS counter, it must first be created with counter-reset.

body {
  /* Initialize counter named 'section' to 0 */
  counter-reset: section; 
}

h2::before {
  /* Increment the counter */
  counter-increment: section; 
  /* Display the counter */
  content: "Section " counter(section) ": "; 
}

4. Nested Counters

You can create nested counters (like 1.1, 1.2) by resetting the counter inside the element that contains the nested items.

ol {
  /* Creates a new instance of the 'section' counter for each <ol> */
  counter-reset: section;
  list-style-type: none;
}

li::before {
  counter-increment: section;
  /* counters() allows a separator string for nested scopes */
  content: counters(section, ".") " ";
}

5. Starting Value

You can specify a starting value for counter-reset.

body {
  /* Starts at 4 (so the first increment makes it 5) */
  counter-reset: my-counter 4; 
}

You can also increment by a specific value (even negative).

h2 {
  counter-increment: my-counter -1; /* Decrement by 1 */
}

programming/css/css programming/css/pseudo-classes-and-pseudo-elements