CSS: How to have multiple counters in nested counters

jojonmarijon

So I am trying to use nested counters in CSS but I am not quite familiar with how it works, This is what I have so far,

This is what I have so far

But what I was hoping to happen is that every time there is an unordered list, when I start an ordered list it resets back to 1. 2. 3. and so on perhaps similar to this

Something Like This

https://codepen.io/jojonmarijon/pen/OJZZPBK?editors=1100

HTML

<ul>
  <li>A</li>
  <li>B</li>
  <li>C</li>
  <ol>
    <li>AA</li>
    <li>BB</li>
    <li>CC</li>
    <ol>
      <li>AAA</li>
      <li>BBB</li>
      <li>CCC</li>
      <ul>
        <li>AAAA</li>
        <li>BBBB</li>
        <ol>
          <li>AAAAA</li>
          <li>BBBBB</li>
          <li>CCCCC</li>
        </ol>
        <li>CCCC</li>
      </ul>
      <li>DDD</li>
    </ol>
  </ol>
</ul>

CSS

    ol {
        counter-reset: section;
        list-style-type: none;
    }

    ul {
        counter-reset: section;
    }

    ol > li {
        counter-increment: section;
    }

    ol > li::marker {
        content: counters(section, ".") ". ";
        left: -4px;
    }

    ul > li:before {
        counter-increment: section;
        content: '';
    }
Tiddo

I don't think a generic solution is possible with just CSS at the moment: counter-reset: <name> will create a nested counter if there is already a counter with <name> in the hierarchy. And there's no way to access the parent, or "unnest" the parent counter. You'd need a counter with a different name to achieve your result.

So I think you'll need to choose between 2 sub-optimal solutions:

  1. Implement it in JS
  2. Support it only for up to n levels deep, for some low level of n. E.g. something like this:
ol {
  counter-reset: section;
  list-style-type: none;
}

ol > li {
  counter-increment: section;
}

ol > li::marker {
  content: counters(section, ".") ". ";
  left: -4px;
}

/* Level 1 */

ul ol {
  counter-reset: nested;
}

ul ol > li {
  counter-increment: nested;
}

ul ol > li::marker {
  content: counters(nested, ".") ". ";
}

/* level 2 */

ul ul ol {
  counter-reset: nested2;
}

ul ul ol > li {
  counter-increment: nested2;
}

ul ul ol > li::marker {
  content: counters(nested2, ".") ". ";
}

/* etc. */

See also: https://codepen.io/Tiddo/pen/vYjjRRx?editors=1100

I think that in practice, you likely only need to support it 3-5 levels deep at most, so you might be able to get away with the hardcoded solution.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

TOP Ranking

HotTag

Archive