HOME C C++ PYTHON JAVA HTML CSS JAVASCRIPT BOOTSTRAP JQUERY REACT PHP SQL AJAX JSON DATA SCIENCE AI

CSS Counters

CSS counters are a feature in CSS that allow you to increment or decrement numerical values using CSS. They are particularly useful for automatically numbering elements or keeping track of the occurrence of certain types of elements.

CSS counters are defined using the counter-reset and counter-increment properties.

counter-reset: This property is used to initialize or reset a counter to a specified value. It creates or resets a counter associated with a specific CSS selector.

Example

/* Resetting a counter */
.container {
    counter-reset: my-counter;
}
You can click on above box to edit the code and run again.

Output

counter-increment: This property is used to increment or decrement the value of a counter. It increments or decrements the value of a counter each time the specified CSS selector matches an element.

Example

/* Incrementing a counter */
.item {
    counter-increment: my-counter;
}

Once a counter has been initialized and incremented, you can use the counter() or counters() function to display the value of the counter in your CSS.

Example

/* Displaying the value of a counter */
.counter-value::before {
    content: counter(my-counter);
}

Here's a simple example that demonstrates the use of CSS counters to automatically number HTML list items:

Example

 /* Initialize counter */
    .container {
        counter-reset: my-counter;
    }
    /* Increment counter for list items */
    .container li {
        counter-increment: my-counter;
    }
    /* Display counter value */
    .container li::before {
        content: counter(my-counter) ". "; /* Add numbering and a period after each list item */
    }
You can click on above box to edit the code and run again.

Output

  • Milk
  • Bread
  • cookies

In this example, each list item (<li>) inside the .container div is automatically numbered using CSS counters. The counter-reset property initializes the counter, and the counter-increment property increments it for each list item. Finally, the content property is used to display the value of the counter before each list item.