Home > Blockchain >  HTML Headings Numbering Resets Unexpectedly
HTML Headings Numbering Resets Unexpectedly

Time:01-27

I want headings in a simple HTML web page to be hierarchically numbered. I thus have:

body {
  counter-reset: h1counter;
}

h1:before {
  content: counter(h1counter) ".\0000a0\0000a0";
  counter-increment: h1counter;
  counter-reset: h2counter;
}

h2:before {
  content: counter(h1counter) "." counter(h2counter) ".\0000a0\0000a0";
  counter-increment: h2counter;
}
<h1>Section 1</h1>
<h2>Subsection 1</h2>
<h2>Subsection 2</h2>
<h1>Section 2</h1>
<h2>Subsection 1</h2>
<h2>Subsection 2</h2>
<h1>Section 3</h1>
<h2>Subsection 1</h2>
<h2>Subsection 2</h2>

But this displays as follows:

1.  Section 1
1.1.  Subsection 1
1.1.  Subsection 2
2.  Section 2
2.1.  Subsection 1
2.1.  Subsection 2
Section 3
3.1.  Subsection 1
3.1.  Subsection 2

Obviously, the second numbering digit of the Subsection 2 <h2> headings should be 2, but it doesn't increment (as if counter-increment: h2counter; wasn't executed), like it does for the <h1> headings.

What did I miss?

CodePudding user response:

You should move the "h2counter reset" line in a single h1 selector. The final result for the style should be like this:

body {
    counter-reset: h1counter;
}
h1 {
    counter-reset: h2counter;
}
h1:before {
    content: counter(h1counter) ".\0000a0\0000a0";
    counter-increment: h1counter;
}
h2:before {
    content: counter(h1counter) "." counter(h2counter) ".\0000a0\0000a0";
    counter-increment: h2counter;
}
<h1>Section 1</h1>
<h2>Subsection 1</h2>
<h2>Subsection 2</h2>
<h1>Section 2</h1>
<h2>Subsection 1</h2>
<h2>Subsection 2</h2>
<h1>Section 3</h1>
<h2>Subsection 1</h2>
<h2>Subsection 2</h2>

CodePudding user response:

HTML

<h1>Section 1</h1>
<h2>Subsection 1</h2>
<h2>Subsection 2</h2>
<h1>Section 2</h1>
<h2>Subsection 1</h2>
<h2>Subsection 2</h2>
<h1>Section 3</h1>
<h2>Subsection 1</h2>
<h2>Subsection 2</h2>

CSS

body {counter-reset:section;}
h1 {counter-reset:subsection;}
h1:before
{
counter-increment:section;
content:"Section " counter(section) ". ";
    font-weight:bold;
}
h2:before 
{
counter-increment:subsection;
content:counter(section) "." counter(subsection) " ";
}
  •  Tags:  
  • Related