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 countercounter-increment
- Increments a counter valuecontent
- Inserts generated contentcounter()
orcounters()
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
counter-reset: section;
}
h2::before {
counter-increment: section;
content: "Section " counter(section) ": ";
}
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
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) " ";
}
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
counter-reset: section;
list-style-type: none;
}
li::before {
counter-increment: section;
content: counters(section,".") " ";
}
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 |