Use the “counter” property to turn any element into a numbered list. Similar to how the ordered list tag works <ol> . Very useful if you’re creating a documentation site where you need to automatically number the headings or create a table of contents 👍
There are 2 parts to this step. You need to define your counter and give it a name.
1a. Define Counter I have named mine tidbit-counter . We give it a name so we can call it in the later steps.
1
counter-reset: tidbit-counter;
1b. Initialize Counter
The next part is to initialize your counter. By default, the value of this is 0 . Note, this number is not displayed. This is just where you setting the “starting” of your counter. So if I had set this number to be 20 , then my output would go 21, 22, 23...etc . Assuming that my increment is 1 (more on this later).
Once you set up your counter. Now you can start incrementing it. Here’s the syntax for this property:
1
counter-increment: <counter name> <integer>;
As you noticed, it accepts an integer argument. That means you are not restricted to just increasing the counter value by 1 . Below chart assumes counter-reset is 0 .
counter-increment
Output
1 (default)
1, 2, 3 …etc
5
5, 10, 15…etc
-5
-5, -10, -15…etc
And yes, you can also pass in a negative integer to decrease the counter. Okay, let’s see how that would be implemented:
Finally, to display the counter, we need to pass the counter function as the value for our content property. The content property is often the way for us to display value in our HTML through CSS. Here’s the syntax for our counter function.
1
counter(<counter name>, <counter list style>)
By default, we have been working numbers. And that’s the default counter list style or in the docs, they call it style . But you can also pass in other styles .
CSS counter doesn’t replace <ol> . If you have a numbered ordered list, then you should absolutely still use <ol> because it’s important that you structure your HTML using the proper semantics. Semantic markup is crucial for Accessibility and SEO.
for the win
Here’s an example where I should use <ol> . In this instance, I’m just listing a bunch of rules. It makes semantic sense to use an ordered list <ol> .
1 2 3 4 5 6
<h2>Rules</h2>
<ol> <li>You do not talk about Fight Club</li> <li>You do not talk about Fight Club</li> </ol>
CSScounter for the win
Here’s an example where I would use CSS counter . In this instance, I have a documentation page using headings h2 and paragraphs p . In this example, having a counter is more of a visual presentation. This example would make sense using CSS counter .
1 2 3 4 5 6 7
<article> <h2>What is Vue.js?</h2> <p>Vue is a progressive framework for building user interfaces.</p>
<h2>Getting Started</h2> <p>Visit Vuejs.org to learn more!</p> </article>
1 2 3
1: What is Vue.js? Vue is a progressive framework for building user interfaces. 2: Getting Started Visit Vuejs.org to learn more!