Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to nest multiple counters in css?

Tags:

html

css

I would like to nest two different numbering with CSS, in order to obtain automatic numbering looking like this:

1 Section1

1-1 SubSection1

1-2 SubSection1

2 Section2

2-1 SubSection2

2-2 SubSection2

Here is my attempt to achieve that:

<head>
    <style>
    body
    {
        counter-reset: sectioncount;
    }

    h1:before
    {
        counter-increment: sectioncount 1;
        counter-reset: subsectioncount;
        content: counter(sectioncount) " ";
    }

    h2:before
    {
        counter-increment: subsectioncount 1;
        content: counter(sectioncount) "-" counter(subsectioncount) " ";
    }
    </style>
</head>

<body>    
    <h1>Section1</h1>
    <h2>SubSection 1</h2>
    <h2>SubSection 2</h2>        
    <h1>Section2</h1>
    <h2>SubSection 1</h2>
    <h2>SubSection 2</h2>    
</body>

but the subsection counter does not increment. I can't figure out why and how to fix this. The question is : what is the proper way to achieve this in CSS ?

like image 527
Archimondain Avatar asked Jan 27 '26 17:01

Archimondain


1 Answers

To be honest, I don't know exactly why, but in this case setting counters for host elements (not pseudo elements) fixes your issue:

/**
  @note 2021-09 this rule is not necessary and
    ⚠ at this moment breaks subsequent resets in Firefox ⚠
  @see https://bugzilla.mozilla.org/show_bug.cgi?id=1729498
*/
body {
  counter-reset: sectioncount subsectioncount;
}

h1 {
  counter-increment: sectioncount 1;
  counter-reset: subsectioncount;
}

h1:before {
  content: counter(sectioncount) " ";
}

h2 {
  counter-increment: subsectioncount 1;
}

h2:before {
  content: counter(sectioncount) "-" counter(subsectioncount) " ";
}
<h1>Section1</h1>
<h2>SubSection 1</h2>
<h2>SubSection 2</h2>
<h1>Section2</h1>
<h2>SubSection 1</h2>
<h2>SubSection 2</h2>
like image 175
myf Avatar answered Jan 29 '26 10:01

myf



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!