Search code examples
cssnestedcss-counter

CSS: nested ol start numbering at 1.1


I have a nested set of related topics/subtopics, using <ol>. The CSS I have so far works great from the top of the tree, but users are able to click on subtopics, and I'm redrawing the nested set of <ol>, starting from where the user clicked. My problem is, I need to respect the chapter numbers, etc.

So, if a typical structure might be this:

Vehicles
  1. Automobile
    1.1 Street
      1.1.1 Sedan
      1.1.2 Coup
      1.1.3 Truck
    1.2 Race
      1.2.1 
  2. Rail
    2.1 Locomotive
    2.2 High Speed
    2.3 Uni

And the user clicks on 1.1 Street, I need to show:

1.1 Street
  1.1.1 Sedan
  1.1.2 Coup
  1.1.3 Truck

The CSS I have so far is this:

ol li {display:block;}
ol > li:first-child {counter-reset: item;}
ol > li {counter-increment: item; position: relative;}
ol > li:before {content:counters(item, ".") ". "; position: absolute; margin-right: 100%; right: 10px;}

I've tried a few variations with a second counter, but no dice! Complicating this problem, the tree can be infinitely deep, so any hard coded solution is out. Thanks!


Solution

  • You can wrap your list in an outer <ol><li> block, then update your CSS to show the counter for the nested content

    ol ol > li:before {content:counters(item, ".") ". "; position: absolute; margin-right: 100%; right: 10px;}
    

    Here's a demo:

    https://jsfiddle.net/q34wdw5p/