Using CSS Counters
The CSS counters are variables which we can increment or decrement with the specific property. With the help of it, we can achieve some generic iteration like in a programming language.
This method can be used for some creative solution which includes a counter for some repeating part of your code.
To control your counters you need the counter-reset and counter-increment property and also the counter() and counters() function pair. This methodology not worth anything without the counter display, for that we can use the simplified content property.
The behavior is simple. You have an unordered list, and you want to count your li items. You specify a new counter on the ul element, and you increment it on the li elements.
We can define our counter variable with the counter-reset property; for this, we have to give any name and optionally a start value. The default start data is zero. This property goes to the wrapper element.
With the use of the counter-increment property, we can increase or decrease our counter value. This property also has an optional second value which specifies the increment/decrement volume.
The counter() function is responsible for the dump. The place of the dump is the content property because this is where you can give back data to your HTML through CSS. The function has two parameters; the first is the name of the counter variable and the second is the counter type (optional).
This function does the same job as the counter() function. The main difference is that with the counters() you can embed the counter iterations to another like in a multi-level ul list. It has three parameters, the first is the name of the counter, the second is the separator, and the third is the counter type (optional).
Use Case #1 – Automatic Documentation Issue Tracking
This solution can be handy when you have some repetitive element, and you also want to count them.
We create a counter-reset on our .container wrapper element. After this, we set a counter-increment for the items with issues class name. In the end, we write out the value of the counter with the help of the content property on the .issues:before items.
Use Case #2 – Nested Lists
Using the counters() function, we can make nested list counter as we do in our text editor program.
Use Case #3 – Counting Checked Checkboxes
Using the input fields :checked pseudo-class value we can check if a checkbox is checked and if so we can increment our counter.
Summary in a Video
Steve Griffith made an excellent and informative overall video on this topic. It is covering almost everything you need to know about CSS counters.
Other Use Case(s)
Follow us on Twitter
Do you want to support and help us? A Twitter following or a sharing means a lot to us. Thank you!