Using CSS counters
CSS counters are like "variables" maintained by CSS whose values can be incremented by CSS rules (to track how many times they are used).
A CSS counter is created with the counter-reset
property.
- The
counter-reset
property creates or resets one or more counters. - The
counter-reset
property is usually used together with thecounter-increment
property and thecontent
property.
Here's a brief explanation of how CSS counters work:
Counter Initialization
You can initialize a counter with the counter-reset property. This sets the initial value of the counter.
For example:
.counter {
counter-reset: myCounter 0;
}
In the above example:
- We initializes a counter named
myCounter
with an initial value of 0.
Counter Increment
You can increment the value of a counter using the counter-increment property. This is typically done when a specific element is encountered in the HTML.
For example:
.counter-item::before {
counter-increment: myCounter;
content: "Counter Value: " counter(myCounter);
}
In this example:
- each element with the class
counter-item
will increment themyCounter
counter, and the counter value will be displayed before the content of the element.
Displaying Counter values
To display the value of a counter, you can use the counter()
function within the content property. This function takes the name of the counter as an argument and inserts its current value.
For example:
.counter-item::before {
counter-increment: myCounter;
content: "Counter Value: " counter(myCounter);
}
In this example:
- each element with the class
counter-item
will increment themyCounter
counter, and the counter value will be displayed before the content of the element.
Nesting Counters
CSS counters can also be nested, allowing you to create numbered or labeled sub-lists within a larger list.
As an example:
Editor
CSS Counter Properties
Here's a list of the 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 |