Using counters

To use a CSS counter, it must first be reset to a value (0 by default). To add the value of a counter to an element, use the counter() function. The following CSS adds to the beginning of each element “Section:”.

CSS >

body {
  counter-reset: number;                    /* Set the number counter to 0 */
}
h4::before {
  counter-increment: number;                /* Increment the number counter */
  content: "Section " counter(number) ": "; /* Display the counter */
}

HTML >

<h4>Introduction</h4>
<h4>Body</h4>
<h4>Conclusion</h4>

Output >

Section 1: Introduction

Section 2: Body

Section 3: Conclusion

Demo


Nesting counters

A CSS counter can be especially useful to make outlined lists because a new instance of a CSS counter is automatically created in child elements. Using the counters() function, a string can be inserted between different levels of nested counters. For example this CSS:

CSS >

ol {
  counter-reset: number;                /* Creates a new instance of the
                                            number counter with each ol
                                            element */
  list-style-type: none;
}
li::before {
  counter-increment: number;            /* Increments only this instance
                                            of the number counter */
  content: counters(number,".") " ";    /* Adds the value of all instances
                                            of the number counter separated
                                            by a ".". */
                                         /* if you need to support < IE8 then
                                            make sure there is no space after
                                            the ',' */
}


HTML >

<ol>
  <li>item</li>          
  <li>item               
    <ol>
      <li>item</li>      
      <li>item</li>      
      <li>item           
        <ol>
          <li>item</li>  
          <li>item</li>
        </ol>
      </li>
      <li>item</li>      
    </ol>
  </li>
  <li>item</li>          
  <li>item</li>          
</ol>

Output >

  1. 1. item
  2. 2. item
    1. 2.1. item
    2. 2.2. item
    3. 2.3. item
      1. 2.3.1. item
      2. 2.3.2. item
    4. 2.4. item
  3. 3. item
  4. 4. item

Demo