← Back toFront-end Tips

Append leading zeros to ordered list items

Written byPhuoc Nguyen
Created
16 Mar, 2021
Category
Tip
Tags
CSS
Setting the `list-style-type` property to the below value will append zero number to items of an ordered list (`ol`):
ol {
list-style-type: decimal-leading-zero;
}
However, it only has effect with the items whose indices are less than 10. It means that if our list has more than 100 items, then they will be prefixed as following:
01. Item
02. Item
...
09. Item
10. Item
...
99. Item
100. Item
...
In order to fix that issue, we can use the CSS counter. Each item holds the current value of the counter which is incremented by one in the next item:
ol {
counter-reset: items;
list-style-type: none;
}
li {
counter-increment: items;
}
To prefix an item with its associate counter value, the `::before` pseudo element comes to the rescue.
li:before {
content: '00' counter(items) '. ';
}
li:nth-child(n + 10)::before {
content: '0' counter(items) '. ';
}
li:nth-child(n + 100)::before {
content: counter(items) '. ';
}
The `:nth-child(n+10)` selector indicates the items whose indices are greater or equal to 10. It will override the styles applied for `li::before` elements. In the same way, `:nth-child(n+100)` overrides the styles of `:nth-child(n+10)`.

See also

Questions? 🙋

Do you have any questions? Not just about this specific post, but about any topic in front-end development that you'd like to learn more about? If so, feel free to send me a message on Twitter or send me an email. You can find them at the bottom of this page.
I have a long list of upcoming posts, but your questions or ideas for the next one will be my top priority. Let's learn together! Sharing knowledge is the best way to grow 🥷.

Newsletter 🔔

If you're into front-end technologies and you want to see more of the content I'm creating, then you might want to consider subscribing to my newsletter.
By subscribing, you'll be the first to know about new articles, products, and exclusive promotions.
Don't worry, I won't spam you. And if you ever change your mind, you can unsubscribe at any time.