Sub topic 16
Nesting Lists
This chapter assumes you can write a basic ul or ol with li items and that you know what elements and attributes are. Nesting lets you show a hierarchy, such as categories with sub-items, an outline, or a multi-level menu.
The core rule
A nested list goes inside the li of its parent item. It does not go directly inside the parent ul or ol. The only permitted children of a ul or ol are li elements (plus script-supporting elements), so a bare ul placed between items is invalid.
<ul>
<li>Fruit
<ul>
<li>Apples</li>
<li>Pears</li>
</ul>
</li>
<li>Vegetables</li>
</ul>The text "Fruit" and the inner ul both belong to the same li. This tells the browser, and assistive technology, that Apples and Pears are children of Fruit.
Mixing list types
You can nest any list type inside any other. An ordered list of steps can contain an unordered list of options, and the reverse is also fine.
<ol>
<li>Prepare the page
<ul>
<li>Create <code>index.html</code></li>
<li>Add a <code>title</code></li>
</ul>
</li>
<li>Open the file in a browser</li>
</ol>The outer list is numbered because order matters. The inner list is bulleted because those tasks have no required order.
How browsers display nesting
By default, each level is indented. Browsers usually change the bullet style for deeper ul levels, commonly from a disc to a circle to a square. Numbering in an inner ol restarts at 1 and is independent of the outer list.
flowchart TDThe structure is easier to see as a tree:
Common errors
| Mistake | Why it is a problem | Fix |
|---|---|---|
| Putting `<ul>` directly inside another `<ul>` | Invalid HTML. Browsers render it, but parsers and screen readers may misread the hierarchy. | Move the inner list inside the parent `li`. |
| Closing the parent `li` before the nested list | The nested list is no longer part of that item. | Put the inner list before the parent's `</li>`. |
| Nesting deeper than needed | Deep hierarchies are hard to scan and navigate. | Keep to two or three levels where you can. |
| Using nesting only for indentation | Lists should express real hierarchy, not layout. | Use CSS for spacing. |
Nesting in practice
Nested lists are the basis for dropdown and multi-level navigation menus. Each top-level li holds a link and, where needed, a nested ul of sub-links. The next chapter builds on this pattern.
Exercise
What is wrong with this markup, and how do you fix it? <ul><li>Fruit</li><ul><li>Apples</li></ul></ul>
Show answer
The inner ul is a direct child of the outer ul, which is invalid because only li elements may be direct children. Move the inner ul inside the Fruit li: <ul><li>Fruit<ul><li>Apples</li></ul></li></ul>.