CSS Nested Ordered Lists
It seems very silly that with all of the power of CSS and the push for semantic HTML, that the ordered list in HTML has fairly basic functionality, or rather, it’s missing something that is useful on most websites that are built these days.
Let’s take our standard Terms and Conditions. Normally this is broken down, contract-style, into Section 1 then Sub Section 1.4 etc. Now in HTML we represent this as:
<ol>
<li>Why are HTML Ordered lists rubbish?
<ol>
<li>Bad HTML
<ol>
<li>This could be badly nested HTML</li>
<li>or have other problems such as
<ol>
<li>poorly typed</li>
<li>cake in the keyboard</li>
<li>developer is drunk</li>
</ol>
</li>
<li>or maybe even just tiredness</li>
</ol>
</li>
</ol>
</li>
</ol>
This is nice and proper HTML but the numerals are just single figures rather than being 1.3.2.
CSS 2.1 to the rescue
Thankfully there is a solution (for some browsers) in the form of CSS 2.1. In CSS 2.1, you can define counters. These allow us to store the current level and populate it as we loop through the nested lists. With a bit of jiggery pokery, we can then output the number before the list item.
ol {
counter-reset: item;
}
ol li:before {
content: counters(item, ".") ". ";
counter-increment: item;
}
Now when you render this in Firefox/Safari you get nicely numbered list items.
Drawbacks
There are some drawbacks. It appears that IE (how did we know that was coming?) breaks at the statement. This means that anything appearing after it will not work, so put it at the end of your stylesheet.
Tags: CSS, html, nested, ordered list
This entry was posted on Wednesday, December 10th, 2008 at 2:31 pm and is filed under CSS. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.