How to Create Nested Lists in HTML
We will introduce proper methods to create nested lists in HTML.
Creating Nested Lists in HTML
We can create an ordered list with the ol
tag and an unordered list with the ul
tag. Inside these tags, we use the li
tag to create the list of items.
There will be cases when we have to make a list of items inside another list of items. Such a list structure is called a nested list, and in this article, we will explore the proper way to write a nested list.
The structure of the unordered list is as follows.
<ul>
<li> Item 1 </li>
<li> Item 2 </li>
<li> Item 3 </li>
</ul>
Let’s suppose we have to add a few list items under the Item 1
. In such a scenario, we should use the ul
tag inside the particular li
tag. Then, we can write the list of items inside the ul
tag using the li
tags.
For example, create a ul
tag, and create three li
tags inside the ul
tag. Write the texts Dogs
, Cats
, and Hamsters
inside the li
tags as shown below in the example.
Inside the first li
tag, create a ul
tag. Create two li
tags inside the ul
tags and write the list items as Siberian Husky
and German Shepherd
.
This is the correct way of writing nested lists in HTML.
Example Code:
<ul>
<li> Dogs
<ul>
<li> Siberian Husky </li>
<li> German Shepherd </li>
</ul>
</li>
<li> Cats </li>
<li> Hamster </li>
</ul>
While creating a nested list, we should avoid writing the nested ul
tag after closing the li
tags. Such practice does not involve any nested lists.
The wrong practice of writing a nested list is shown below.
<ul>
<li> Dogs </li>
<ul>
<li> Siberian Husky </li>
<li> German Shepherd </li>
</ul>
<li> Cats </li>
<li> Hamsters </li>
</ul>
We have closed the li
tag of the Dog
item list before writing the sublists. Then, we created a ul
tag to add the sublists.
Although the result looks the same in the above two examples, we should follow the first approach. We should ensure that the ul
tag is the child of the li
tag it belongs.
Thus, we can properly write nested lists in HTML.
Subodh is a proactive software engineer, specialized in fintech industry and a writer who loves to express his software development learnings and set of skills through blogs and articles.
LinkedIn