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 on the listitem (<li>). For uls I – evidently – chose list-style: square; and for ols I chose list-style: 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, this would result in this snippet of CSS code:

ul li {
	list-style: square;
}

ol li {
	list-style: 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: square;
}

ol {
	list-style: decimal;
}

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

Nested lists (correct)
(Click for demo)

There, nothing to it πŸ™‚

Join the Conversation

4 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. 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.