CSS Counters

In This article, I will explain CSS Counters.

CSS counters are a feature in CSS that allows you to automatically number elements in a document or create other types of automatic counters. With CSS counters, you can create numbered lists, chapter headings, and other types of sequential or hierarchical numbering systems.

CSS counters work by creating a named counter that can be incremented or decremented each time a specific element is encountered in the document. The counter-reset property is used to create a new counter and set its initial value. The counter-increment property is used to increment the value of the counter each time the element is encountered.

Here’s an example of how you could use CSS counters

<!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>
<br>
<h1>Chand Dakhara:</h1>
<h2>.Net MVC devloper</h2>
<h2>Front end devloper</h2>
</body>
</html>

The above CSS code defines two counters: section and subsection. The body element has a counter-reset property that creates the section counter and sets its initial value to 0. The h1 element also has a counter-reset property that creates the subsection counter and sets its initial value to 0.

The h1::before selector uses the counter-increment property to increment the value of the section counter each time an h1 element is encountered. It then uses the content property to display the value of the section counter as a prefix to the h1 element, with the text “Section” and a period separator.

The h2::before selector uses the counter-increment property to increment the value of the subsection counter each time an h2 element is encountered. It then uses the content property to display the value of the section and subsection counters separated by a period, followed by a space.

In the HTML document, there are two h2 elements that follow the h1 element. Because the h1 element resets the subsection counter, the first h2 element has a value of “1.1”, and the second h2 element has a value of “1.2”.

Output:

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories