CSS counter numbering nested list items incorrectly

When using a CSS counter() to display a custom count on an ordered list, be sure to display the count on the ::before pseudo element and not the ::after, like so:

ol {
  list-style: none;
  counter-reset: counterName;

  li {
    &:before {
      content: counter(counterName) "";
    }
}

If you put it on the ::after as I did, the pseudo element messes up the count if you start nesting list items. Which makes sense when you think about it semantically, but it took me a long time to realise this.

Thanks to Adam Burt for helping me find the solution.

Resources

Using CSS counters - CSS: Cascading Style Sheets | MDN
CSS counters let you adjust the appearance of content based on its location in a document. For example, you can use counters to automatically number the headings in a webpage, or to change the numbering on ordered lists.
counter-set - CSS: Cascading Style Sheets | MDN
The counter-set CSS property sets CSS counters to the given values.

Like this post? Got a question?

Reply via: Email, Bluesky, Mastodon, Twitter