CSS Counters

These counters are similar to variables and those values can be incremented by CSS rules to track how many times they are used.

They facilitate simple CSS based incrementing and display of a number for generated content. Following is the list of properities it has:-

  • counter-reset: It is used to create or reset a counter.
  • counter-increment: It is used to increment the counter value.
  • content: It is used to insert generated content.
  • counter() or counters() function: It is used to add the value of a counter to an element.

Note:- Before using a CSS counter, it must be created with counter-reset.

Input:-

Index.html
	
<body>   
   <h2>Heading 1</h2>  
   <h2>Heading 2</h2>  
   <h2>Heading 3</h2>  
   <h2>Heading 4</h2>  
</body>
Style.css
body {  
    counter-reset: section;  
}  
h2::before {  
    counter-increment: section;  
    content: "Section " counter(section) ": ";  
} 

Output:-


Nesting Counter

We can also create counters within the counter. It is called nesting of a counter.

Input:-

Index.html
	
<body>   
    <h1>Frontend Languages</h1>
    <h2>HTML</h2>  
    <h2>CSS</h2>  
    <h2>Javascript</h2>  
    <h2>React Javascript</h2>  
    <h1>Backend Languages</h1>
    <h2>PHP</h2>  
    <h2>NodeJS</h2>  
    <h2>Go Language</h2>  
    <h2>Mongo DB</h2>
</body>
Style.css
body {  
    counter-reset: section;  
}  
h1 {  
    counter-reset: subsection;  
}  
h1::before {  
    counter-increment: section;  
    content: "Section " counter(section) ". ";  
}  
h2::before {  
    counter-increment: subsection;  
    content: counter(section) "." counter(subsection) " ";  
} 

Output:-


Different level of Nesting Counter

We can create outlined lists by using nesting counters. It facilitates us to insert a string between different levels of nested counters.

Input:-

Index.html
	
<body>   
    <ol>  
       <li>item</li>  
       <li>item  
         <ol>  
           <li>item</li>  
           <li>item</li>  
           <li>item  
             <ol>  
                <li>item</li>  
                <li>item</li>  
                <li>item</li>  
             </ol>  
          </li>  
          <li>item</li>  
        </ol>  
      </li>  
      <li>item</li>  
      <li>item</li>  
   </ol>
</body>
Style.css
ol {  
    counter-reset: section;  
    list-style-type: none;  
}  
  
li::before {  
    counter-increment: section;  
    content: counters(section,".") " ";  
}  

Output:-