CSS Counters

Home / CSS / CSS Counters

CSS Counters


CSS-Counters:

CSS counters are a powerful feature that allows you to automatically number HTML elements or generate counters for various purposes. They are particularly useful for creating lists, tables, and other structured content. Here's an introduction to CSS counters with examples:

1. Create a Counter:

To use counters, you need to define them in your CSS using the counter-reset property. You give your counter a name, and it starts at a specific value.

 
<style>
    /* Define a counter named 'myCounter' starting at 1 */
    body {
      counter-reset: myCounter 1;
    }
  </style>

2. Increment a Counter:

You can increment the counter using the counter-increment property. This is typically done when certain HTML elements are encountered.


 <style>
    /* Increment 'myCounter' whenever an element with class 'list-item' is encountered */
    .list-item {
      counter-increment: myCounter;
    }
  </style>

3. Display a Counter:

You can display the value of a counter using the content property and the counter() function.


 <style>
    /* Display the value of 'myCounter' before each element with class 'list-item' */
    .list-item::before {
      content: counter(myCounter) ". ";
    }
  </style>

Here's an example of using CSS counters to create a numbered list:


<!DOCTYPE html>
<html>
<head>
    <style>
        body {
            counter-reset: myCounter 1;
        }
        .list-item {
            counter-increment: myCounter;
        }
        .list-item::before {
            content: counter(myCounter) ". ";
        }
    </style>
</head>
<body>
    <p class="list-item">Item 1</p>
    <p class="list-item">Item 2</p>
    <p class="list-item">Item 3</p>
</body>
</html>

In this example, each paragraph with the class "list-item" is automatically numbered using the myCounter counter.

4. Resetting Counters:

You can reset a counter to a specific value if needed. For example, you might want to restart numbering for a new section.


<style>
    /* Reset 'myCounter' to 1 at the start of a new section */
    .section {
      counter-reset: myCounter 1;
    }
  </style>

5. Nesting Counters:

You can nest counters within each other. This is useful for more complex structures like nested lists.


 <style>
    /* Define counters for outer and inner lists */
    .outer-list {
      counter-reset: outerCounter;
    }
    .inner-list {
      counter-reset: innerCounter;
    }
    .outer-list-item {
      counter-increment: outerCounter;
    }
    .inner-list-item {
      counter-increment: innerCounter;
    }
    .outer-list-item::before {
      content: counter(outerCounter) ". ";
    }
    .inner-list-item::before {
      content: counter(outerCounter) "." counter(innerCounter) ". ";
    }
  </style>