Halvor William Sanden
Colour modes

Nesting HTML list elements

There are two ways to nest lists in HTML, but only one communicates correctly.

Correct structure #

Let’s say we are making a table of contents (TOC) for an article page. Beyond the page title of h1, the article has two heading levels, h2 and h3. We make the following structure for the first level:

<ul>
  <li>
  	<a>Link to h2</a>
  </li>
  <li>
  	<a>Link to h2</a>
  </li>
</ul>

For the second level, the nested ul goes inside the li. We add a new list element inside the list item to which it belongs:

<ul>
	<li>
		<a>Link to h2</a>
		<ul>
			<li>
				<a>Link to h3</a>
			</li>
			<li>
				<a>Link to h3</a>
			</li>
		</ul>
	</li>
	<li>
		<a>Link to h2</a>
	</li>
</ul>

I don’t know how many times I have mistakenly added a new ul inside the ul as a sibling to the related li element just to be reminded that only li is allowed directly inside ul. It makes sense when I see it in connection with the information structure.

The same goes for ordered and declaration lists, but the latter has some additional syntax. All of these can be styled using elements as selectors.

Wrong structure #

The not recommended way is to put the nested list directly inside a separate list item element. That will sever the connection between the list item parent and the new level. In terms of our example, it would be like having an level 3 heading without a level 2 heading. If we change the ul to ol, it’s even more apparent that something’s not quite right. I don’t see anywhere this would be useful. While we can do it, we probably have a problem elsewhere in our document or list structure and should review that.

<!-- technically correct, but structurally wrong -->
<ul>
	<li>
		<a>Link to h2</a>
	</li>
	<li>
		<ul>
			<li>
				<a>Link to h3</a>
			</li>
			<li>
				<a>Link to h3</a>
			</li>
		</ul>
	</li>
	<li>
		<a>Link to h2</a>
	</li>
</ul>

References #