CSS Counters

Being somewhat similar to variables, the CSS Counters can be incremented by CSS rules. They are thus used to track the number of times they are used. A simple CSS based incrementing can thus be achieved by using the CSS Counters. A CSS counter is created using the counter-reset.

CSS Counter Properties:

The properties used with CSS counter are listed below:

Counter-reset:

Use: To create or reset a counter.

Counter-increment:

Use: To increment the counter value.

Content:

Use: To insert generated content.

Counter() or Counters() function:

Use: To add the value of a counter to an element.

Example:

<!DOCTYPE html>
<html>
<head>
<style>
body {
  counter-reset: topic;
}
 
h3::before {
  counter-increment: topic;
  content: "Topic " counter(topic) ": ";
}
</style>
</head>
<body>
<h2>List of Topics:</h2>
<h3>HTML</h3>
<h3>CSS</h3>
<h3>JavaScript</h3>
<h3>JQuery</h3>
</body>
</html>

Output:

Explanation:

In the above example, we created a counter is created whose value is incremented for each <h3> element and adds “Topic <value of the counter>:” to the beginning of each <h3> element.

CSS Nesting Counters:

Creating counters within a counter is called nesting of a counter.

Example:

<!DOCTYPE html>  
<html>  
<head>  
<style>  
body {  
    counter-reset: topic;  
}  
h2 {  
    counter-reset: subtopic;  
}  
h2::before {  
    counter-increment: topic;  
    content: "Topic " counter(topic) ". ";  
}  
h3::before {  
    counter-increment: subtopic;  
    content: counter(topic) "." counter(subtopic) " ";  
}  
</style>  
</head>  
<body>  
<h2>Fruits:</h2>  
<h3>Apple</h3>  
<h3>Banana</h3>  
<h3>Mango</h3>  
<h3>Peach</h3>  
<h3>Guava</h3>  
 
<h2>Flowers:</h2>  
<h3>Lily</h3>  
<h3>Orchid</h3>  
<h3>Rose</h3>  
<h3>Hibiscus</h3>    
</body>  
</html>

Output:

Explanation:

In the above example, a counter is created for the section and within the section, another nesting counter named subsection is created.

Level of nesting counters:

To create outlined lists, the nesting counters can be used. A string can also be inserted between different levels of nested counters.

Example:

<!DOCTYPE html>  
<html>  
<head>  
<style>  
ol {  
    counter-reset: topic;  
    list-style-type: none;  
}  
 
li::before {  
    counter-increment: topic;  
    content: counters(topic,".") " ";  
}  
</style>  
</head>  
<body>  
<h2>Example:</h2>  
<ol>  
  <li>Fruits</li>  
  <li>Flowers  
    <ol>  
      <li>Rose</li>  
      <li>Lily</li>  
      <li>Tulip</li>     
          <li>Orchid</li>  
          <li>Hibiscus</li>  
          <li>Lotus</li>  
  <li>Tulip</li>  
  <li>Sunflower</li></ol> 
  <li>Vegetables</li> 
</ol>  
</body>  
</html>

Output:

Explanation:

In the above example, we used two levels of nested counters in CSS.

Please Share