CSS Counters
CSS counters are pretty cool. It allows CSS to be able to keep track of the number of times a certain element is used. Right now in this playground, there are absolutely no numbers in the HTML code even though there are numbers in the rendered output. This is due to CSS variables!
Counter Reset
To start off, you can use the CSS property counter-reset
to declare a new CSS counter variable. It also resets the value of the CSS counter. The counter-reset
property accepts a counter name and its new value. A good example is counter-reset: myCounter 5
which resets the myCounter
CSS counter to the value 5
.
Counter Reset
.list {
counter-reset: myCounter 0;
}
Counter Increment
The counter-increment
CSS property is used to increment a CSS counter. A value of counter-increment: myCounter
would increment myCounter
by 1. You can also add in a optional numeric value to choose how much the counter increases. A value of counter-increment: myCounter 5
would increment myCounter
by 5 every time.
Every time counter-increment
is found on an element, it’s associated variable is incremented. In this playground, wherever an element with the class list-item
is found, the myCounter
counter is incremented.
Counter Increment
.list-item {
counter-increment: myCounter 1;
}
Counter Content
To have your CSS counter displayed, the CSS property content
has to be used within the ::before
or ::after
pseudo class. The CSS function counter()
is used to display your CSS counter. The counter()
function requires the name of the CSS counter and an optional Counter Style. The widget below uses a few in built counter styles.
List Item Content
.list-item::before {
content: counter(myCounter, decimal);
}
Nested CSS Counters
In this playground, we have nested lists in the HTML. Every nested .list
is able to create its own version of the myCounter
CSS counter. To view all of the versions of the myCounter
CSS counter, we can use the counters()
function. counters()
requires the CSS counter name, a string to separate each variable, and an optional Counter Style.
List Item Content
.list-item::before {
content: counters(myCounter, ', ', decimal);
}