Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Using CSS counter to number headings that are individually wrapped by div

I’m trying to make headings numbered using CSS counters on HTML code rendered from the CodeMirror markdown editor. I’ve already seen tao’s answer on a similar topic, but as you can see below, in my case, each heading is wrapped by an individual div which makes it faulty.

.wrapper {
  counter-reset: a b c; /* ... */
}
h1.numbered {
  counter-increment: a;
  counter-reset: b;
}
h2.numbered {
  counter-increment: b;
  counter-reset: c;
}
/* ... */

h1.numbered::before {
  content: counter(a) " ";
}
h2.numbered::before {
  content: counter(a) "." counter(b) " ";
}
/* ... */
<div class="wrapper">
    <div><h1 class="numbered">Heading 1</h1></div>
    <div><h2 class="numbered">Heading 1.1</h2></div>
    <div><h2 class="numbered">Heading 1.2</h2></div>
    <div><h1 class="numbered">Heading 2</h1></div>
    <div><h2 class="numbered">Heading 2.1</h2></div>
    <div><h2 class="numbered">Heading 2.2</h2></div>
</div>

I believe the reason is behind the initiation scope of counters (by counter-reset), possibly preventing them from holding the correct value or following the internal logic.

Please do let me know if you can think of any solution to this without the need to change the HTML structure.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You have to "initialise" (reset) both counters on their common ancestor. Values will be then bound to it and usable across all children. To really reset (in fact just set) sub-heading level, you have to use counter-set instead.

body { counter-reset: h1 h2; }
h1 {
 counter-increment: h1;
 counter-set: h2 0;
}
h2 {
 counter-increment: h2;
}
h1::before { content: counter(h1) ' '; }
h2::before { content: counter(h1) '.' counter(h2) ' '; }
<div><h1>Heading 1</h1></div>
<div><h2>Heading 1.1</h2></div>
<div><h2>Heading 1.2</h2></div>
<div><h1>Heading 2</h1></div>
<div><h2>Heading 2.1</h2></div>
<div><h2>Heading 2.2</h2></div>

counter-reset creates new "scope" in descendants and adjacent consecutive siblings. counter-set sets the value.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading