A Guide to CSS counter
5 min readMar 25, 2019
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 👍
div {
/* Define & Initialize Counter */
counter-reset: tidbit-counter;
}h2::before {
/* Increment Counter */
counter-increment: tidbit-counter;/* Display Counter */
content: counter(tidbit-counter) ": ";
}
HTML
<div>
<h2>HTML</h2>
<h2>CSS</h2>
<h2>JS</h2>
</div>
How the counter property work
There are 3 steps to get the counter to work:
- Define & Initialize Counter
- Increment Counter
- Display Counter
1. Define & Initialize Counter
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.
counter-reset: tidbit-counter;
1b. Initialize Counter