How to Create an Ordered List with Nested Counters
Table of Contents
Ordered lists are useful in HTML because they allow you to create a list of items that have a counter associated with them.
However, sometimes you need to nest ordered lists within each other, but want to keep the counters separate.
In this post, we'll learn how to display nested ordered lists with counters.
How to create a nested ordered list with counters
To start off, let's create a basic ordered list.
HTML<ol>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ol>
- HTML
As you can tell if you try to run the example above, there's nothing special going on it, just a basic list.
But now let's see what happens if we try to nest ordered lists.
HTML<ol>
<li>Item 1
<ol>
<li>Item 1.1</li>
<li>Item 1.2</li>
<li>Item 1.3</li>
</ol>
</li>
<li>Item 2
<ol>
<li>Item 2.1</li>
<li>Item 2.2</li>
<li>Item 2.3</li>
</ol>
</li>
<li>Item 3</li>
</ol>
- HTML
The browser will automatically create separate counters for each nested list.
However, with some simply CSS, we can create a counter that uses both the parent and children counter together, so you always know what level you're on:
HTML<ol>
<li>Item 1
<ol>
<li>Item 1.1</li>
<li>Item 1.2</li>
<li>Item 1.3</li>
</ol>
</li>
<li>Item 2
<ol>
<li>Item 2.1</li>
<li>Item 2.2</li>
<li>Item 2.3</li>
</ol>
</li>
<li>Item 3</li>
</ol>
CSSol {
counter-reset: item;
}
li {
display: block;
counter-increment: item;
}
li:before {
content: counters(item, ".") " ";
}
- HTML
- CSS
Now you can see that the list items go from:
BASH1. Item 1.1
to
BASH1.1 Item 1.1
Conclusion
In this post, we learned how to create a nested ordered list with counters that display both the parent and child counter.
Simply use a bit of CSS to make the counters display the parent and child counter together when they are nested.
Thanks for reading!
- Managing PHP Dependencies with Composer
- Getting Started with Express
- How to Set Up Cron Jobs in Linux
- How to build a Discord bot using TypeScript
- Getting User Location using JavaScript's Geolocation API
- Getting Started with Moment.js
- Learn how to build a Slack Bot using Node.js
- Getting Started with React
- Setting Up Stylus CSS Preprocessor
- Setting Up a Local Web Server using Node.js
- Using Axios to Pull Data from a REST API
- How To Create a Modal Popup Box with CSS and JavaScript