Introduction to CSS Counters
CSS Counters is one of the powerful and attractive tools in the CSS language that allows you to create automatic numbering. This feature is commonly used in lists, where you want to number items. Although this capability exists in HTML, CSS Counters allows you to have greater control over the styling of these numbers.
One of the interesting applications of CSS Counters is that it can be used not only for numbering but also for other purposes. For example, it can be used in pages that have multiple sections, to give each section a unique number.
The structure of CSS Counters is such that you start by defining a name for the counter and then use a variable, which you can utilize and modify. With this work, you will be able to display the numbers in various ways and improve the user experience on websites.
In the following, we will illustrate the implementation of CSS Counters with a simple example. This example will practically show how to use counters in CSS.
Code Example for CSS Counters
<style>
body {
counter-reset: section; /* Create and reset the counter */
}
h2::before {
counter-increment: section; /* Increment the counter value */
content: "Section " counter(section) ". "; /* Display the counter value */
}
</style>
<h2>Title 1</h2>
<p>Some content for the first section.</p>
<h2>Title 2</h2>
<p>More content for the second section.</p>
Line Explanations
body { counter-reset: section; }
In this line, a counter named section is created and its value is reset to zero.
h2::before { counter-increment: section; }
Here, the section counter is incremented each time an h2 tag appears.
content: "Section " counter(section) ". "
In this part, the counter is displayed along with the specified text.