Forum Bugs

Problem using heading counters

dalcocer
I took an example from the book "CSS: The Definitive Guide" (3rd ed.) to generate numbered headings. The problem is that the section counter is not getting reset properly.

Output from Prince:
1. The Secret Life of Salmon
1.1. Introduction
2. Habitats
2.2. Ocean
2.3. Rivers
3. Spawning
3.4. Fertilization
3.5. Gestation
3.6. Hatching


Expected output (verified using Opera 9.26):
1. The Secret Life of Salmon
1.1. Introduction
2. Habitats
2.1. Ocean
2.2. Rivers
3. Spawning
3.1. Fertilization
3.2. Gestation
3.3. Hatching


Input HTML file:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html>
  <head>
    <title>Numbered headings</title>
    <link rel="stylesheet" href="hdr-num-bug.css" title="My Style" type="text/css" media="screen,print">
  </head>

  <body>
    <h1>The Secret Life of Salmon</h1>
    <h2>Introduction</h2>

    <h1>Habitats</h1>
    <h2>Ocean</h2>
    <h2>Rivers</h2>

    <h1>Spawning</h1>
    <h2>Fertilization</h2>
    <h2>Gestation</h2>
    <h2>Hatching</h2>
  </body>
</html>


CSS file:
h1:before {
    counter-reset: section;
    counter-increment: chapter;
    content: counter(chapter) ". ";
}
h2:before {
    counter-reset: subsect;
    counter-increment: section;
    content: counter(chapter) "." counter(section) ". ";
}
h3:before {
    counter-increment: subsect;
    content: counter(chapter) "." counter(section) "." counter(subsect) ". ";
}


If anyone has a work-around for this problem will be appreciated.
mikeday
Apply the counter-reset property to the heading element itself, not the ::before pseudo-element, which is treated as a child of the heading and will only reset the counter within the heading element scope. This should solve the problem:
h1 { counter-reset: section }
h1:before {
    counter-increment: chapter;
    content: counter(chapter) ". ";
} 
dalcocer
Thanks for the clarification, I didn't realize that the :before would be treated as a child. FWIW, here's the final CSS that works:

h1 {
    counter-reset: section;
}
h1:before {
    counter-increment: chapter;
    content: counter(chapter) ". ";
}
h2 {
    counter-reset: subsect;
}
h2:before {
    counter-increment: section;
    content: counter(chapter) "." counter(section) ". ";
}
h3:before {
    counter-increment: subsect;
    content: counter(chapter) "." counter(section) "." counter(subsect) ". ";
}