CSS Counters

CSS Counters

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. CSS counters are an implementation of Automatic counters and numbering in CSS 2.1.

To work with CSS counters we will use the following properties:

Using counters

Example:

<!DOCTYPE html>
<html>
<head>
<style>
body {  
counter-reset: section;
}  
h2::before {
    counter-increment: section;
    content: "Section " counter(section) ": ";
}

</style>
</head>
<body>
<h1>Web Development Tutorials:</h1>
<h2>Html Tutorials</h2>
<h2>Css Tutorials</h2>
<h2>Javascript Tutorials</h2>
</body>
</html>
Try it with the Editor

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.

<!DOCTYPE html>
<html>
<head>
<style>
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) " ";
}
</style>
</head>
<body>
<h1>HTML tutorials:</h1>
<h2>Html Tutorials</h2>
<h2>Css Tutorials</h2>

<h1>Scripting tutorials:</h1>
<h2>JavaScript</h2>
<h2>VBScript</h2>

<h1>XML tutorials:</h1>
<h2>XML</h2>
<h2>XSL</h2>
</body>
</html>
Try it with the Editor

A counter can also be useful to make outlined lists because a new instance of a counter is automatically created in child elements. Here we use the counters() function to insert a string between different levels of nested counters:

<!DOCTYPE html>
<html>
<head>
<style>
body {  
counter-reset: section;
}  
h2::before {
    counter-increment: section;
    content: "Section " counter(section) ": ";
}

</style>
</head>
<body>
<h1>Web Development Tutorials:</h1>
<h2>Html Tutorials</h2>
<h2>Css Tutorials</h2>
<h2>Javascript Tutorials</h2>
</body>
</html>
Try it with the Editor

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.

<!DOCTYPE html>
<html>
<head>
<style>
ol {
    counter-reset: section;
    list-style-type: none;
}

li::before {
    counter-increment: section;
    content: counters(section,".") " ";
}
</style>
</head>
<body>
<ol>
  <li>item</li>
   <li>item     
    <ol>
      <li>item</li>
      <li>item</li>
      <li>item</li>
   </ol>
  </li>
   <li>item</li>
   <li>item</li>
</ol>
</body>
</html>
Try it with the Editor