Automatic HTML numbered headings

already 2 comments

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) " ";

How this works is quite simple:

  • for each parent element, set the counter-reset property to start counting from 0 ;
  • for each to-be-numbered element, print the actual value of the counter then add 1 to the value, using counter-increment, so that the next element as an incremented value ;

You can see a live version here.

Source: Automatic counters and numbering, from W3C Recommandation

2 Responses to “Automatic HTML numbered headings”

  1. Kristian says:

    Simply beautiful!
    No more manual numbering inside the heading tags, with the updates require when introducing a new chapter.

Leave a Reply