views:

84

answers:

3

Can anyone explain me why <ul> elementa cannot be empty?

And why this HTML:

<ul>
    <li class="header">
        <a href="#">Work</a>
        <ul/>
    </li>
    <li class="header">
        <a href="#">New</a>
        <ul/>
    </li>
    <li class="header">
        <a href="#">Ungrouped</a>
        <ul/>
    </li>
    <li class="header">
        <a href="#">Offline</a>
        <ul/>
    </li>
</ul>

is rendered like this:

  • Work
    • New
      • Ungrouped
        • Offline
+1  A: 

Because browsers (usually) don't support self closing XML-style tags. This will work:

<ul>
    <li class="header">
        <a href="#">Work</a>
        <ul></ul>
    </li>
    <li class="header">
        <a href="#">New</a>
        <ul></ul>
    </li>
    <li class="header">
        <a href="#">Ungrouped</a>
        <ul></ul>
    </li>
    <li class="header">
        <a href="#">Offline</a>
        <ul></ul>
    </li>
</ul>

For more details see: Can a span be closed using <span />?

Kobi
In this case, "usually" means at least Firefox, Safari, Opera, Chrome and IE8... :)
zorglub76
@zorglub76 - I never tested it, but the question I linked suggests it will work well with a different mime type: `text/xml` instead of `text/html` - which most servers serve.
Kobi
+4  A: 

<ul> is not a valid self-closing tag, so browsers may treat it as though it has not been closed properly. You should always use a closing </ul> tag.

For a list of valid self-closing tags, see:

http://stackoverflow.com/questions/97522/what-are-all-the-valid-self-closing-tags-in-xhtml-as-implemented-by-the-major-br

Andy E
@David Dorward: How can it be valid if the specification *requires at least one list item in it*? A self closing `ul` will not validate because it's empty.
Andy E
Actually, this will work: <ul></ul>. So, it can be empty, but not without the closing tag
zorglub76
+1  A: 

What is the sound of one hand clapping?

A list with zero items in it doesn't make sense from a document point of view, and HTML is a document markup language.

The specification therefore defines a list as requiring at least one list item in it.

<!ELEMENT UL - - (LI)+                 -- unordered list -->

As for your second question, in HTML Compatible XHTML only elements which are defined as being EMPTY (i.e. those in which the end tag is forbidden in HTML) may (and must) use self-closing tag syntax.

David Dorward
It says "(LI)+", but in all the major browsers "<ul></ul>" works...
zorglub76
That's because browsers are designed to cope with vast amounts of crap written by people who don't know HTML.
David Dorward