Search code examples
htmlcsscss-counter

CSS list counter increase level


HTML

<ol>
  <li>item1
    <ol>
      <li>item2</li>
    </ol>
  </li>
  <li>item1
    <ol>
      <li>item2</li>
      <li>item3</li>
    </ol>
  </li>
</ol>

SCSS

ol {
  counter-reset: item;
  li {
    display: block
  }
  li:before {
    content: counters(item, ".") ". ";
    counter-increment: item
  }
}

Now the list is ordered like this:

  1. item1

1.1. item2

  1. item1

2.1. item2

2.2. item3

Is there any way how I can increment ordering by one level at the beggining of the list? Second <ol> would start with 2: 2.1. item1

1.1. item1

1.1.1. item2

1.2. item1

1.2.1. item2

1.2.2. item3

-------second ol in the same parent---------

2.1. item1

2.1.1. item2

2.2. item1

2.2.1. item2

2.2.2. item3

Pen is here: http://codepen.io/simPod/pen/wawOLd


Solution

  • You could set up an additional counter and only update it on the outer lists (which can be selected via body > ol)

    Updated Codepen

    body {
      counter-reset: outer;
    }
    body > ol {
      counter-increment: outer;
    }
    ol {
      counter-reset: item;
    }
    ol li {
      display: block;
    }
    ol > li:before {
      content: counter(outer)"." counters(item, ".")". ";
      counter-increment: item;
    }
    <ol>
      <li>item1
        <ol>
          <li>item2</li>
        </ol>
      </li>
      <li>item1
        <ol>
          <li>item2</li>
          <li>item3</li>
        </ol>
      </li>
    </ol>
    <ol>
      <li>item1
        <ol>
          <li>item2</li>
        </ol>
      </li>
      <li>item1
        <ol>
          <li>item2</li>
          <li>item3</li>
        </ol>
      </li>
    </ol>