Nesting lists allows you to create hierarchical structures within your HTML documents, making complex information more organized and readable. This is achieved by placing one list inside an item of another list, commonly used for outlines, table of contents, or multi-level menus.
Example 1: Basic Ordered and Unordered Nesting
<!DOCTYPE html>
<html>
<head>
<title>Nested Lists Example</title>
</head>
<body>
<h1>Grocery List</h1>
<ul> <li>Fruits
<ul> <li>Apples</li>
<li>Bananas</li>
</ul>
</li>
<li>Vegetables
<ol> <li>Carrots</li>
<li>Broccoli</li>
</ol>
</li>
</ul>
</body>
</html>
Explanation: This example demonstrates nesting an unordered list within an <li>
of another unordered list, and an ordered list within another <li>
. This creates a simple two-level grocery list.
Example 2: Nested Navigation Menu
<!DOCTYPE html>
<html>
<head>
<title>Nested Navigation</title>
</head>
<body>
<nav>
<ul> <li>Home</li>
<li>Products
<ul> <li>Electronics</li>
<li>Apparel</li>
</ul>
</li>
<li>About Us</li>
</ul>
</nav>
</body>
</html>
Explanation: This code shows a common use case for nested lists: creating a dropdown or multi-level navigation menu. The "Products" link has a sub-menu of categories.
Example 3: Nested Definitions List
<!DOCTYPE html>
<html>
<head>
<title>Nested Definition List</title>
</head>
<body>
<dl> <dt>HTML</dt>
<dd>HyperText Markup Language
<dl> <dt>HTML5</dt>
<dd>The latest version of HTML.</dd>
</dl>
</dd>
<dt>CSS</dt>
<dd>Cascading Style Sheets</dd>
</dl>
</body>
</html>
Explanation: Here, a definition list (<dl>
) is nested within another definition's description (<dd>
). This is useful for defining terms with sub-definitions, like a glossary.
Example 4: Task List with Sub-tasks
<!DOCTYPE html>
<html>
<head>
<title>Nested Task List</title>
</head>
<body>
<h1>Project Tasks</h1>
<ol> <li>Phase 1: Planning
<ul> <li>Requirements gathering</li>
<li>Resource allocation</li>
</ul>
</li>
<li>Phase 2: Development
<ol> <li>Frontend</li>
<li>Backend</li>
</ol>
</li>
</ol>
</body>
</html>
Explanation: This example illustrates how to create a multi-level task list using a combination of ordered and unordered nested lists. This helps organize project workflows.
Example 5: Nested List for Survey Options
<!DOCTYPE html>
<html>
<head>
<title>Nested Survey Options</title>
</head>
<body>
<h2>Survey Question: Favorite Colors</h2>
<ul> <li>Primary Colors
<ul> <li>Red</li>
<li>Blue</li>
<li>Yellow</li>
</ul>
</li>
<li>Secondary Colors
<ul> <li>Green</li>
<li>Orange</li>
<li>Purple</li>
</ul>
</li>
</ul>
</body>
</html>
Explanation: This code snippet shows how nested lists can be used to present survey or questionnaire options with sub-categories. This provides a clear, structured way to display choices.