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.

Prologue

The way I used to style lists, was to set the list-type-type on the listitem (<li>). For unordered lists (<ul>) I – evidently – chose list-style-type: square; and for ordered lists (<ol>) I chose list-style-type: decimal;. I know, very basic but don’t run away yet, I’m trying to get somewhere here 😉

Old Skool

When implementing the code above, I used to implement it as follows:

ul li {
	list-style-type: square;
}

ol li {
	list-style-type: decimal;
}

Lists do indeed show up fine, but – however – when nesting lists, things go wrong, and you’ll get a result like the one below:

Nested lists (wrong)
(Click for demo)

The reason things go wrong is that the last CSS rule (ol li { ... }) overwrites the first one (ul li { ... })

Yes I know this can quickly be overridden by adding some extra selectors like ul ol li { ... } and ol ul li { ... } yet the problem will remain there when having a third nested level.

The right way to do it

The correct way to do it is to set your list-style declarations directly on the ul and ol elements, as shown below:

ul {
	list-style-type: square;
}

ol {
	list-style-type: decimal;
}

This will result in a correct numbering/bulleting when having nested lists:

Nested lists (correct)
(Click for demo)

There, nothing to it 🙂

Published by Bramus!

Bramus is a frontend web developer from Belgium, working as a Chrome Developer Relations Engineer at Google. From the moment he discovered view-source at the age of 14 (way back in 1997), he fell in love with the web and has been tinkering with it ever since (more …)

Unless noted otherwise, the contents of this post are licensed under the Creative Commons Attribution 4.0 License and code samples are licensed under the MIT License

Join the Conversation

6 Comments

  1. Thanks for the tip! I will definitely tell this to my friend who is always having trouble styling her lists / bullets on her site. Hmmm, I think I can brighten up her day. I’m glad I passed by here at your site. Thanks again!

  2. I use to get nested lists wrong all the time. It was a pain in the butt. After a while though, I finally got a hang of it. It took quite a few trips to w3c validator though.

  3. hi
    always appriciate cleaning up my html skils. I actually gave up lists a while back, but maybe I will get back into it, thanks

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.