CSS Counters

CSS Tutorial

CSS Advanced

CSS Responsive

CSS Grid

CSS Counters

Automatic Numbering with Counters

CSS counters are similar to “variables”. The values of the variable can be incremented using CSS rules.

To work with CSS counters, use the following properties:

  • counter-reset – Creates or resets a counter.
  • counter-increment – Increments a counter value.
  • content – Inserts generated content.
  • counter() or counters() function – Adds the value of a counter to an element.

To use a CSS counter, it should be created with a counter-reset.

The example creates a counter for the page (in the body selector), then the counter value is incremented for each <h2> element and is added to the “Section <value of the counter>:” to the beginning of each <h2> element:

HTML
				
					<h1>Using CSS Counters</h1>
<h2>HTML Tutorial</h2>
<h2>CSS Tutorial</h2>
<h2>JavaScript Tutorial</h2>
<h2>Python Tutorial</h2>
<h2>SQL Tutorial</h2>
				
			
CSS
				
					body {
  counter-reset: section;
}

h2::before {
  counter-increment: section;
  content: "Section " counter(section) ": ";
}
				
			

Output

css counters

Nesting Counters

The following example creates one counter for the page (section) and one counter for each <h1> element (subsection). The “section” counter will be counted for each <h1> element with “Section <value of the section counter>.”, and the “subsection” counter will be counted for each <h2> element with “<value of the section counter>.<value of the subsection counter>”.

HTML
				
					<h1>HTML/CSS Tutorials</h1>
<h2>HTML</h2>
<h2>CSS</h2>
<h2>Bootstrap</h2>
<h2>W3.CSS</h2>
<h1>Scripting Tutorials</h1>
<h2>JavaScript</h2>
<h2>jQuery</h2>
<h2>React</h2>
<h1>Programming Tutorials</h1>
<h2>Python</h2>
<h2>Java</h2>
<h2>C++</h2>
				
			
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

nesting counters

A counter can also be used to create outlined lists as new instance of a counter is automatically generated in child elements. The counters() function  is used to insert a string between different levels of nested counters.

HTML
				
					<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>
<ol>
  <li>item</li>
  <li>item</li>
</ol>
				
			
CSS
				
					ol {
  counter-reset: section;
  list-style-type: none;
}

li::before {
  counter-increment: section;
  content: counters(section,".") " ";
}
				
			

Output