Style Nested Ordered List With CSS

June 9, 2023 by Andreas Wik

nested ordered list

Let’s look at how you can use CSS to style a nested ordered list so that the numbers appear like 1.2., 1.3., 1.3.1., 1.3.2. and so on.

We will end up with something similar to this:

See the Pen Untitled by Andreas Wik (@andreaswik) on CodePen.

 

HTML

We start by creating a nested ordered list with some lorem ipsum content so we have something to work with:

<ol>
    <li>
        Lorem ipsum dolor sit amet
        <ol>
            <li>Massa eget egestas purus viverra</li>
            <li>Morbi tristique senectus et netus et malesuada fames ac turpis</li>
            <li>Massa tempor nec feugiat nisl pretium fusce id velit ut:
                <ol>
                    <li>mauris pellentesque pulvinar pellentesque habitant morbi tristique senectus;</li>
                    <li>est ultricies integer quis auctor elit sed vulputate</li>
                </ol>
            </li>
        </ol>
    </li>
</ol>

 

CSS

Let’s move onto the CSS. I won’t go into details on each and every line but will focus on the most important parts that actually matter to make it work.

First we grab the ordered list ol selector and create a counter with counter-reset and name it item.

ol {
  counter-reset: item;
  margin: 0;
  padding: 0;
}

 

To have the list display nicely, let’s set the li selector’s display property to table.

li {
  display: table;
  margin: 15px 0;
}

 

We are now down to the final piece of CSS. Let’s create a before pseudo element with li::before and set counter-increment to increment the value of the counter item we created earlier. We also define how we want the content to show up with the content property, showing a dot after each number.

li::before {
  counter-increment: item;
  content: counters(item, ".") ". ";
  display: table-cell;
  padding-right: 8px;
}

 

That should be it!

As usual, here is a CodePen you can mess around with:

See the Pen Untitled by Andreas Wik (@andreaswik) on CodePen.

 

Share this article

Recommended articles

@awikio