CSS Counters


Pizza

Hamburger

Hotdogs

CSS counters are like little storage units in CSS. We can increase their values using CSS rules to keep count of how many times they've been used. These counters help us change how things look depending on where they are in the document.


Automatic Numbering With Counters

CSS counters act like "variables." These variables can be increased by CSS rules (which will keep track of how many times they are used).

We'll use these properties when working 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

To make a CSS counter work, you need to start by setting it up using the counter-reset property.

In this example, we're making a page counter within the body section. We start with a counter and increase its value for every <h2> element. We also add 'Section (counter value):' at the beginning of each <h2> element.

Example

body {
  counter-reset: section;
}

h2::before {
  counter-increment: section;
  content: "Section " counter(section) ": ";
}
Try it Yourself »

Nesting Counters

In this example, we have two counters: one for the main page content and another for each heading. The 'page' counter increments every time we encounter an <h1> heading, and it displays as Section <value of the page counter>.' The 'heading' counter increments for each <h2> heading, and it displays as '<value of the page counter>. <value of the heading 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) " ";
}
Try it Yourself »

You can use a counter to create lists with outlines. When you have nested elements, a new counter is made for each child element automatically. To do this, we utilize the counters() function to add a text string between various levels of these nested counters.

Example

ol {
  counter-reset: section;
  list-style-type: none;
}

li::before {
  counter-increment: section;
  content: counters(section,".") " ";
}
Try it Yourself »

 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