Nested Lists
A table of contents has chapters with sections inside them. A site menu has categories with pages inside them. A recipe's steps can have sub-steps. These are lists inside lists, and HTML handles them by nesting. There is exactly one rule to get right.
The rule
The inner list lives inside an li, never loose in the outer list.
To nest, put a complete new list inside the li it belongs to, after that item's text and before its closing </li>:
<ul>
<li>Home</li>
<li>Courses
<ul>
<li>Maths</li>
<li>Science</li>
</ul>
</li>
<li>Contact</li>
</ul>Why inside the li? Two reasons:
- The rule of lists: a
ulorolmay only havelielements as direct children. Aulsitting between twolielements breaks that rule. - The meaning: Maths and Science belong to Courses. Putting their list inside the Courses item says exactly that, and screen readers announce the nesting level so users know where they are.
You can mix types. An ordered list of steps can hold an unordered list of options within one step:
<ol>
<li>Choose a base:
<ul>
<li>Rice</li>
<li>Millet</li>
</ul>
</li>
<li>Add the vegetables.</li>
</ol>Nesting can go deeper, but more than two or three levels usually means the content needs rethinking or splitting into sections with headings.
The shortcut
Find the parent item, then open its door. Locate the li the sub-items belong to, and put the new list before that li closes.
Find the parent
Step 2 is "Prepare the tea". Its sub-steps are "boil water" and "add leaves".
The trap is closing the parent li first and putting the inner list after it. It often looks almost right, which is why it is so common.
Indentation helps enormously here. Indent each inner list one level deeper than its parent li, as in the examples, and a misplaced list becomes visible at a glance: the inner ul should always appear indented under an item's text, never lined up with the li elements around it.
Drills
Answer fast — trust the rule.
Where does a nested list go?
Which snippet is valid?
Can an ol be nested inside a ul?
Why do screen reader users benefit from correctly nested lists?
Remember
- Nest a list inside the
liit belongs to, before thatlicloses. - Shortcut: find the parent item, open its door, insert a whole list, then close the parent.
- Trap: putting the inner list between
lielements, directly inside the outer list.
