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

Advertisements

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.

>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.

Leave a ReplyCancel reply