A Guide to CSS counter

Samantha Ming
5 min readMar 25, 2019
CodeTidbit by SamanthaMing.com

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:

  1. Define & Initialize Counter
  2. Increment Counter
  3. 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

--

--

Samantha Ming

Frontend Developer sharing weekly JS, HTML, CSS code tidbits🔥 Discover them all on samanthaming.com 💛