counters property

Image Tutorials

Definition and Usage

CSS counters are, in essence, variables maintained by CSS whose values may be incremented by CSS rules to track how many times they’re used. This lets you adjust the appearance of content based on its placement in the document.

The value of a counter is manipulated through the use of counter-reset and counter-increment can be displayed on a page using the counter() or counters() function of the content property.


Examples

1 <h3>Introduction</h3>
2 <h3>Body</h3>
3 <h3>Conclusion</h3>
1 body {
2   counter-reset: section;           /* Set the section counter to 0 */
3 }
4 h3:before {
5   counter-increment: section;      /* Increment the section counter */
6   content"Section " counter(section) ": "/* Display the counter */
7 }

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 h3 element “Section <the value of the counter>:”.

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, the following CSS:

01 ol {
02   counter-reset: section;                /* Creates a new instance of the
03                                             section counter with each ol
04                                             element */
05   list-style-typenone;
06 }
07 li:before {
08   counter-increment: section;            /* Increments only this instance
09                                             of the section counter */
10   contentcounters(section, "."" ";   /* Adds the value of all instances
11                                             of the section counter separated
12                                             by a ".". */
13 }

HTML:

01 <ol>
02   <li>item</li>          <!-- 1     -->
03   <li>item               <!-- 2     -->
04     <ol>
05       <li>item</li>      <!-- 2.1   -->
06       <li>item</li>      <!-- 2.2   -->
07       <li>item           <!-- 2.3   -->
08         <ol>
09           <li>item</li>  <!-- 2.3.1 -->
10           <li>item</li>  <!-- 2.3.2 -->
11         </ol>
12         <ol>
13           <li>item</li>  <!-- 2.3.1 -->
14           <li>item</li>  <!-- 2.3.2 -->
15           <li>item</li>  <!-- 2.3.3 -->
16         </ol>
17       </li>
18       <li>item</li>      <!-- 2.4   -->
19     </ol>
20   </li>
21   <li>item</li>          <!-- 3     -->
22   <li>item</li>          <!-- 4     -->
23 </ol>
24 <ol>
25   <li>item</li>          <!-- 1     -->
26   <li>item</li>          <!-- 2     -->
27 </ol>
Rate article