Working 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:
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:
There, nothing to it 🙂
Did it wrong for a long time too. Damn you CSS tutorials filled with wrong info!
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!
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.
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