Search code examples
csshtmlheadercss-counter

header tag interfering with css counters headings


When using the usual way to add section numbers to headings by using CSS counters I run into problems when using the header tag.

It somehow seems to interfere with the counter(s)

body {
  counter-reset: h1
}
h1 {
  counter-reset: h2
}
h2 {
  counter-reset: h3
}
h1:before {
  counter-increment: h1;
  content: counter(h1)". "
}
h2:before {
  counter-increment: h2;
  content: counter(h1)"." counter(h2)". "
}
h3:before {
  counter-increment: h3;
  content: counter(h1)"."counter(h2)"." counter(h3)". "
}
<!DOCTYPE HTML>
<html>

<head>
  <title>Headings counting</title>

</head>

<body>
  <header>
    <h1>First chapter</h1>
  </header>
  <h2>Sub Chapter</h2>
  <h2>Sub Chapter</h2>
  <h2>Sub Chapter</h2>
  <h3>Sub sub section</h3>
</body>

</html>

Output is:

  • First chapter
  • 1.1. Sub Chapter
  • 1.1. Sub Chapter
  • 1.1. Sub Chapter
  • 1.0.1. Sub sub section

after removing the header tag output is as expected:

    1. First chapter
  • 1.1. Sub Chapter
  • 1.2. Sub Chapter
  • 1.3. Sub Chapter
  • 1.3.1. Sub sub section

Should the use of the header tag around H1 result in this or not? It does so on Firefox & Edge, not on Chrome & Opera


Solution

  • Simply replace/add header to the counter-reset in h1 declaration rule, depending if you are going to have h1 with or without header tag.

    body {
      counter-reset: h1
    }
    
    header { /* add h1 if you going to use h1 without header tag */
      counter-reset: h2
    }
    h2 {
      counter-reset: h3
    }
    h1:before {
      counter-increment: h1;
      content: counter(h1)". "
    }
    h2:before {
      counter-increment: h2;
      content: counter(h1)"." counter(h2)". "
    }
    h3:before {
      counter-increment: h3;
      content: counter(h1)"."counter(h2)"." counter(h3)". "
    }
    <header>
      <h1>First chapter</h1>
    </header>
    <h2>Sub Chapter</h2>
    <h2>Sub Chapter</h2>
    <h2>Sub Chapter</h2>
    <h3>Sub sub section</h3>