Add Section Numbers to Headings

You have all seen printed documents where the document is broken up into sections and sub-sections with the section numbering being included in the headings. If you have been trying to achieve a similar appearance in a web page then you have probably hard coded all of the section numbering into the headings themselves. Unfortunately doing this means that if you need to add a new section or sub-section then the ones following it all need to be renumbered. If you miss updating one then all of the numbering will be out.

Instead of numbering them manually we can use stylesheets to add the section numbers to all of our sections for us. The following code uses the stylesheet counter and counter-increment attributes to number the H1 headings as sections and will label the H2 headings as sub-sections within those sections. Extending the code to further levels is also possible.

h1:before {content: "Section " counter(section) ". ";
counter-increment: section;
counter-reset: sub-section;
}
h2:before {content: counter(section) "." counter(sub-section) " ";
counter-increment: sub-section;}

With the new ways to divide up a document in HTML 5 the options available for numbering headings becomes even more flexible as you can easily arrange to number the headings within the main content of the page while leaving the headins in any other parts of the page unnumbered.

 

This article written by Stephen Chapman, Felgall Pty Ltd.

go to top

FaceBook Follow
Twitter Follow
Donate