HTML / CSS autonumber headings?

Definitely possible using css counters - just make sure you watch out for browser compatibility...:

This will make h2 get 1., 2., h3 gets 1.1, 2.1, 2.2 etc...

<style>
   body{counter-reset: section}
   h2{counter-reset: sub-section}
   h3{counter-reset: composite}
   h4{counter-reset: detail}

   h2:before{
     counter-increment: section;
     content: counter(section) " ";
   }
   h3:before{
     counter-increment: sub-section;
     content: counter(section) "." counter(sub-section) " ";
   }
   h4:before{
     counter-increment: composite;
     content: counter(section) "." counter(sub-section) "." counter(composite) " ";
   }
   h5:before{
     counter-increment: detail;
     content: counter(section) "." counter(sub-section) "." counter(composite) "." counter(detail) " ";
   }
   </style>

As lpfavreau says, it's the same as another question I believe.

Also note that using css will not change the heading (e.g. selected text will give you the heading without the numbers). This may or may not be desirable. lpfavreau's (accepted) answer will give you the jquery code to modify the heading text.

See MDN: Using CSS counters for details.

3rd Party Edit

I created an example with the css above


2016 update. Please see Stephen's answer below for a proper method in CSS. My answer made sense in 2009 when the browsers and libraries were different. We are now living in a whole new world and the method presented here is outdated. I'm leaving it for the poor souls that are still living in corporate microcosms made of IE7 and tears.


See this other question if you're wondering how to do it in CSS, the answer might be what you are looking for. But titel has a good proposition too, depending how your HTML document is made.

It should be noted that, as Triptych said in another comment, this is of interest only if it's for an internal tool where you have control over which browsers are used and using CSS is worth it because modifying the HTML would be hard for example. Support of this CSS feature is limited.

It would of course be easy to use something like jQuery to do the increment also. Something like this untested snippet:

$(document).ready(function() {
  $('h1').each(function(index) {
    $(this).html((index + 1) + '. ' + $(this).html());
  });
});

Don't forget to include the jquery.js file in your document of course.