Automatic HTML numbered headings

       248 words, 2 minutes

Quoting W3C, “(…)A heading element briefly describes the topic of the section it introduces. Heading information may be used by user agents, for example, to construct a table of contents for a document automatically(…)”. When write a bunch of HTML text, I usually use heading elements to separate chapters and sections. The thing is, by default, those headings aren’t numbered. And when the article is quite long, this may lead to a “where am I” sensation. Here’s a quick way to automatically generate numbered heading elements from standard HTML and CSS code.

First of all, generate some text using paragraphs and headings.

Now, edit your CSS so that it looks like this:

/* numbering headings */
body { counter-reset: H1; } 	/* Create the counter for H1 */
h1:before {
  content: counter(H1) ". "; 	/* Print the H1 number */
  counter-increment: H1; 	/* Add 1 to next H1 */
}
h1 { counter-reset: H2; }
h2:before {
  content: counter(H1) "." counter(H2) " ";
  counter-increment: H2;
}
h2 { counter-reset: H3; }
h3:before {
  content: counter(H1) "." counter(H2) "." counter(H3) " ";
  counter-increment:H3;
}

How this works is quite simple:

You can see a live version here .

Source: Automatic counters and numbering, from W3C Recommandation