Explain Codes LogoExplain Codes Logo

Proper way to make HTML nested list?

html
semantic-html
accessibility
css
Anton ShumikhinbyAnton Shumikhin·Jan 20, 2025
TLDR

Nest a list in HTML by encapsulating a <ul> or <ol> inside an <li> of an outer list. Never forget to close tags. Here's an illustrative example:

<ul> <li>Item 1</li> <li>Item 2 <ul> <li>Subitem 1 <!-- Ah! A wild subitem appears. --></li> <li>Subitem 2 <!-- Subitem 2 joins the battle. --></li> </ul> </li> <li>Item 3</li> </ul>

Item 2 hosts a party with nested friends Subitem 1 and Subitem 2. You can do this for more levels — just kinda keep that party going.

Utilizing different types of lists

HTML offers several types of lists to fit your needs:

  • <ul>: List items here do not follow a specific order (Unordered List).
  • <ol>: Ideal when the sequence is important. Think cooking instructions. (Ordered List).
  • <dl>: Mostly used for terms and definitions. Basically, a flash-card maker.

Semantic HTML and accessibility matters

Semantic HTML gives a meaningful structure to your document, enhancing SEO and accessibility. When you nest your list items correctly, everyone (including screen readers) can navigate easily.

Validation and maintainability

Run your HTML through a 'sanity' check using tools like the W3C Markup Validation Service. It cements your SEO and accessibility efforts. Larger nested lists can be harder to maintain; segregate them into smaller, more manageable pieces if needed.

Ensuring nesting etiquette

Do not place a ul directly within another ul. It's frowned upon in HTML society; ul must be a child of an li:

<!-- Incorrect --> <ul> <ul> <!-- Invalid! --> <li>Subitem <!-- Lone subitem feeling lost. --></li> </ul> </li> <!-- Correct --> <ul> <li> <ul> <!-- Found the right parent! --> <li>Subitem <!-- Happy subitem --></li> </ul> </li> </ul>

Advanced techniques and list dressing

For dealing with dynamic lists or conditional rendering, JavaScript frameworks like React, Vue, or Angular come into play, providing interactive capabilities.

Here are some fashion tips for your list. Dress it up with CSS for custom bullets, spacing, or indentation:

ul { list-style-type: none; /* Bullet-less list. */ padding-left: 20px; /* Let's move things to the right a little. */ } li::before { content: "➤"; /* Your very own custom bullet. Fancy! */ padding-right: 5px; /* Room to breathe. */ }

Deep nesting: proceed with caution

For deeply nested lists, maintaining clarity is critical. Make sure each nested list corresponds only to one parent item. If nesting becomes too deep, consider resorting to tabs, accordions, or sidebar navigation for better user experience.