Search code examples
htmlhtml-listsnested-lists

Proper way to make HTML nested list?


The W3 docs have a nested list example prefixed by DEPRECATED EXAMPLE:, but they never corrected it with a non-deprecated example, nor explained exactly what is wrong with the example.

So which of these ways is the correct way to write an HTML list?

Option 1: The nested <ul> is a child of the parent <ul>:

<ul>
    <li>List item one</li>
    <li>List item two with subitems:</li>
    <ul>
        <li>Subitem 1</li>
        <li>Subitem 2</li>
    </ul>
    <li>Final list item</li>
</ul>

Option 2: The nested <ul> is a child of the <li> it belongs in:

<ul>
    <li>List item one</li>
    <li>List item two with subitems:
        <ul>
            <li>Subitem 1</li>
            <li>Subitem 2</li>
        </ul>
    </li>
    <li>Final list item</li>
</ul>

Solution

  • Option 2 is correct.

    The nested list should be inside a <li> element of the list in which it is nested.

    Link to the MDN article on lists (taken from comment below): HTML lists.

    Link to the HTML5 W3C ul spec: HTML5 ul.

    Note that a ul element may contain exactly zero or more li elements. The same applies to HTML5 ol.

    The description list (HTML5 dl) is similar, but allows both dt and dd elements.

    More notes:

    • dl = definition list.
    • ol = ordered list (numbers).
    • ul = unordered list (bullets).

    MDN link on nesting lists.