Nested counters with headings (h1, h2, etc...)

Elements such as <h1>, <h2> are not nested in a document. They appear as distinct elements but still represent a sort of hierarchy. Here’s how to prepend nested numbers to headings: The h2 counter resets every time an h1 is found. Each <h2> in the document gets a number like x.y. relative to the <h1>.

by Konstantin Rouda

HTML

<section>

<h1>I'm H1 header</h1>
  <p>Paragraph in section 1</p>
  <h2>I'm h2 Header</h2>
</section>


<section>

<h1>I'm H1 header 2</h1>
  <p>Paragraph in section 2</p>
  <h2>I'm h2 Header 2</h2>
</section>

CSS

BODY {
  counter-reset: h1Counter;
}

H1 {
  counter-reset: h2Counter;
}

H1::before {
  content: counter(h1Counter) ") ";
  counter-increment: h1Counter;
  
}


H2::before {
  content: counter(h1Counter) "." counter(h2Counter) ") ";
  counter-increment: h2Counter;
  
}

JavaScript

/*
from: https://blog.logrocket.com/styling-numbered-lists-with-css-counters/
*/