Search code examples
htmlcsscss-counter

Numbering a nested list in a single ol list


I have an ordered list with some li tags in it. I want the The li tags with .sub-item class to be nested li tags. Is there a way I can reset numbering for the li tags having class? The list is as below:

<ol>
  <li>One</li>
  <li>Two</li>
  <li>THree</li>
  <li class="sub-item">Sub three 1</li>
  <li class="sub-item">Sub three 2</li>
  <li>Four</li>
</ol>

Currently I get which makes sense:

  1 One
  2 Two
  3 Three
  4 Sub Three 1
  5 Sub three 2
  6 Four

However using the class 'sub-item' I want this desired behaviour

  1 One
  2 Two
  3. Three
     a Sub three 1
     b Sub Three 2
  4 Four

I can not change the html part of the code, only can write css. Adding nested ol tags will not work in this case as I can not modify the html.


Solution

  • If you can't change your HTML markup, you can simulate nested numbering on a single list with CSS counters.

    You need to remove the default list-style-type and add the counter with pseudo elements.
    .sub-item elements can have their own counter (sub-counter in the following example) that doesn't affect the one set on all the <li> elements (main-counter in the following example) :

    ol {
      counter-reset: main-counter, sub-counter;
      list-style-type:none;
      padding:0;
    }
    li {
      counter-increment: main-counter;
      counter-reset: sub-counter;
    }
    li::before {
      content: counter(main-counter) ". ";
    }
    li.sub-item {
      counter-increment: sub-counter;
      padding-left:1em;
      counter-reset: none;
    }
    li.sub-item::before {
      content: counter(sub-counter, lower-alpha) ". ";
    }
    <ol>
      <li>One</li>
      <li>Two</li>
      <li>THree</li>
      <li class="sub-item">Sub three 1</li>
      <li class="sub-item">Sub three 2</li>
      <li>Four</li>
      <li>Five</li>
      <li>Six</li>
      <li>Seven</li>
      <li class="sub-item">Sub three 1</li>
      <li class="sub-item">Sub three 2</li>
      <li>Eight</li>
    </ol>

    Note that is you need several nested sections, you need to reset the sub-counter on elements without the .sub-item class with the counter-reset property.