Numbering headings and subheadings

numbering headings and subheadings

Have you ever thought of adding numbering to the headings and subheadings rather than manually entering them? This tutorial will give a glance of how to do that using CSS alone.

To start with, we will add the heading tags first.

<div id="container">
  <h1>Heading One</h1>
    <h2>Sub Heading 1</h2>
      <h3>H3 Heading a</h3>
      <h3>H3 Heading b</h3>
  <h1>Heading Two</h1>
    <h2>Sub Heading 1</h2>
    <h2>Sub Heading 2</h2>
      <h3>H3 Heading a</h3>
  <h1>Heading Three</h1>
    <h2>Sub Heading 1</h2>
</div>

Now we will define the CSS properties that will add the numberings for the headings. The CSS properties that we will be using here will be ‘counter-reset’, ‘counter-increment’ and ‘content’.

First we will add a counter which will add numbering to the main headings. This will be defined in the container div where all the headings are present.

#container{
  counter-reset:c1;
}

Now we will define the CSS which will increment and add the numberings to the main headings.

#container h1:before{
  content: counter(c1)". ";
  counter-increment:c1;
}

And then define the counter for the subheadings. We will define it under the main headings ‘h1’ so that whenever a h1 tag is encountered the counter will be resetted.

#container h1{
  counter-reset:c2;
}

And then the CSS which will increment and add the numberings to the subheadings.

#container h2:before{
  content: counter(c1)"."counter(c2)". ";
  counter-increment:c2;
}

And similarly you can add the same for its subheadings as well. And it goes on.

#container h2{
  counter-reset:c3;
}

#container h3:before{
  content:counter(c1)"."counter(c2)"."counter(c3)". ";
  counter-increment:c3;
}

Therefore the full CSS code will look like below

#container{
  counter-reset:c1;
}

#container h1:before{
  content: counter(c1)". ";
  counter-increment:c1;
}

#container h1{
  counter-reset:c2;
}

#container h2:before{
  content: counter(c1)"."counter(c2)". ";
  counter-increment:c2;
}

#container h2{
  counter-reset:c3;
}

#container h3:before{
  content:counter(c1)"."counter(c2)"."counter(c3)". ";
  counter-increment:c3;
}

Leave a Reply

Your email address will not be published.