Styling Ordered Lists with CSS Counters

Using CSS Counters, Josh W Comeau injects his own number in ordered lists. That way he can style the number itself separately.

ol li {
  counter-increment: muffins;
}

ol li:before {
  content: counter(muffins) ". ";
  color: hotpink;
}

ol {
  list-style: none;
  counter-reset: muffins;
}

Apart from styling, I find this technique come in handy to assign the sequence numbers to an element contained somewhere inside the <li>

See the Pen CSS Counter by Bramus (@bramus) on CodePen.

Something that was new to me in his article was the counters (not counter) function, to play nice with nested ordered lists.

Styling Ordered Lists with CSS Counters →

<ol>‘s start and reversed attributes (and more)

Handy for those end-of-year lists 😉

~

Apart from overriding the list style using CSS’s list-style-type (which you should set it on the <ul>/<ol> element, not the <li>), you can also set the list style for unordered lists it from your HTML using the type attribute.

  • a for lowercase letters
  • A for uppercase letters
  • i for lowercase Roman numerals
  • I for uppercase Roman numerals
  • 1 for numbers (default)

⚠️ Do note that this type attribute only is allowed on the <ol> element – not the <ul> element – according to the spec.

~

Additionally, you can also override the value of an <li> element inside an <ol> element using its value attribute:

See how it jumps from 5 to 10? That’s value in action.

Change the marker of a list to any character with list-style-type: <string>

Since CSS Level 2, CSS list-style-type has supported keywords like disc or decimal to define the appearance of the list item marker. Landing in Chrome 79, and also available in Firefox ever since version 39, is the ability to set it to an arbitrary string.

Here’s a pen that demonstrates its behavior / usage:

Let’s hope this land in other browsers too, so that we can stop fiddling with ::before and such to achieve the same result 😉

💁‍♂️ Be sure to set this on the ul element, and not the li‘s or you’ll run into issues with nested lists.

Did this help you out? Like what you see?
Thank me with a coffee.

I don't do this for profit but a small one-time donation would surely put a smile on my face. Thanks!

☕️ Buy me a Coffee (€3)

To stay in the loop you can follow @bramus or follow @bramusblog on Twitter.

How to style your lists properly

ListsWorking with nested lists is not an uncommon practice, yet I’ve noticed that some (and I before) had troubles when working with nested lists of different types (viz. an ol inside an ul or vice versa). However, it shouldn’t be a burden at all, here’s a hat tip, saving you some headaches.

Continue reading “How to style your lists properly”