Creating a counter in CSS is a great way to add numerical values to your web page.
They can be used for a variety of things, such as numbering lists, displaying the number of items in a shopping cart, or even as a way to track user engagement.
In this CSS tutorial, we’ll go over how to create a basic counter in CSS and discuss some of the different ways you can use it on your website.
What is a CSS Counter?
A CSS counter is a variable that can be incremented or decremented in the CSS code.
It is similar to a variable in programming languages like JavaScript or Python.
The value of the counter can then be displayed on the web page using the content
property.
Creating a Basic Counter
The first step in creating a counter is to initialize it using the counter-reset
property.
This is done by setting the counter-reset
property to the value you want the counter to start at.
For example, if you want your counter to start at 1, you would use the following code:
body { counter-reset: my-counter 1; }
Next, you’ll need to create an element that will display the value of the counter.
This can be done using the ::before
or ::after
pseudo-element.
For example, the following code will create a <p>
element that displays the value of the counter:
<p class="counter">Item 1</p>
.counter::before { content: counter(my-counter) ": "; }
Now, you’ll need to increment the counter using the counter-increment
property.
This is done by setting the counter-increment
property to the value you want the counter to increment by.
For example, the following code will increment the counter by 1:
.counter { counter-increment: my-counter 1; }
Using Counters in Lists
One of the most common uses for counters is numbering items in a list.
The following code uses a counter to number the items in an unordered list:
<ul> <li>Item 1</li> <li>Item 2</li> <li>Item 3</li> </ul>
ul { counter-reset: my-counter; } li::before { content: counter(my-counter) ". "; counter-increment: my-counter; }
Conclusion
CSS counters are a powerful tool that can be used to add numerical values to your web pages.
They can be used for a variety of things, such as numbering lists, displaying the number of items in a shopping cart, or even as a way to track user engagement.
With this tutorial, you now know how to create a basic counter in CSS and some of the different ways you can use it on your website.