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 :)

Webdevelopment

4 Responses to How to style your lists properly

  1. Wolf says:

    Did it wrong for a long time too. Damn you CSS tutorials filled with wrong info!

  2. 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!

  3. Poet Blogger says:

    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.

  4. Peter says:

    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 Reply

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

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>