Search code examples
csscss-counter

CSS counter is zero when selector contains class name


I'm trying to use css counter to create nested counter list items for lists with some html class name. I started with sample from mozilla. All works good until I add .nested-list to selector ol.nested-list>li:before.

Here's my css and html.

ol {
  counter-reset: section;
}
ol>li:before {
  counter-increment: section;
}
ol.nested-list {
  list-style-type: none;
}
ol.nested-list>li:before {
  content: counters(section, ".") " ";
}

<ol>
 <li>Entry</li>
  <li>Entry with subentries
    <ol class="nested-list">
      <li>Entry</li>
      <li>Entry with subentries
        <ol>
          <li>Entry</li>
          <li>Entry</li>
        </ol>
      </li>
      <li>Entry</li>
    </ol>
  </li>
  <li>Entry</li>
  <li>Entry with subentries
    <ol>
      <li>Entry</li>
      <li>Entry</li>
    </ol>
  </li>
</ol>

Also on fiddle


Solution

  • Increment the counter for each list item and not it's ::before pseudo element.

    The ::before and ::after elements do not exit without content. Since most of the list items don't have content for their ::before elements, the element doesn't exist and the nested section counter is not incremented correctly.

    ol {
      counter-reset: section;
    }
    
    li {
      counter-increment: section;
    }
    
    ol.nested-list {
      list-style-type: none;
    }
    
    ol.nested-list>li:before {
      content: counters(section, ".") " ";
    }
    <ol>
      <li>Entry</li>
      <li>Entry with subentries
        <ol class="nested-list">
          <li>Entry</li>
          <li>Entry with subentries
            <ol>
              <li>Entry</li>
              <li>Entry</li>
            </ol>
          </li>
          <li>Entry</li>
        </ol>
      </li>
      <li>Entry</li>
      <li>Entry with subentries
        <ol class="nested-list">
          <li>Entry</li>
          <li>Entry</li>
        </ol>
      </li>
    </ol>