XHTML Lists

Thursday, May 22nd, 2008

This one caught me off guard.  I was converting a document to XHTML strict and had a list and sub-list that looked like this:

<ul>
    <li> Thing 1 </li>
    <ul>
        <li> Subthing 1 </li>
        <li> Subthing 2 </li>
    </ul>
    <li> Thing 2 </li>
</ul>

Understandably, XHTML isn’t keen on a child of a ul being something other than a li.   So the logical fix is this:

<ul>
    <li> Thing 1 </li>
    <li>
        <ul>
            <li> Subthing 1 </li>
            <li> Subthing 2 </li>
        </ul>
    </li>
    <li> Thing 2 </li>
</ul>

This creates a mysterious problem.  Your list ends up looking like this:

A strange-looking list

Yep, a little odd.  This happens, it turns out, because XHTML expects the sub-list li to contain some text, just like any li.  This becomes the li that corresponds to the sub-list you are creating, which normally is just the li before the sub-list you are making.  So, our fixed markup looks like this:

<ul>
    <li> Thing 1
        <ul>
            <li> Subthing 1 </li>
            <li> Subthing 2 </li>
        </ul>
    </li>
    <li> Thing 2 </li>
</ul>

Now we have a list that looks like what we expected:

A normal looking list

Ultimately, this feels like a problem with XHTML to me.  The broken behavior we saw seems like it should be outright invalid XHTML, but it is not, according to my validator at least.  In the meantime, if you fall into this trap, hopefully you’ll remember what to do.

2 Comments

  1. If you think about it, it does make sense. Generally you should be nesting list items because they’re ‘children’ of a top-level item, so putting the list within the li associates them with their ‘parent’. However, that parent can be empty/white space, as with most other tags, resulting in the odd extra bullet.

    Comment by Matt Round — May 22, 2008 @ 9:24 pm

  2. I think that XHTML could have been designed so that omitting text here would be an error instead of a situation where you get goofy markup. Imagine something like a sublist element that contains a name and list items. Then, omitting the text would result in an error, but you can express an empty string if you really want to.

    OK OK, so it probably isn’t a “problem” with XHTML per se, but a place where, once you get burned, it becomes clear that it could be improved.

    Comment by gsmith — May 22, 2008 @ 10:07 pm

Leave a comment

About | Other Stuff