CSS Counters work like variables. You can create counters for any HTML element and change the values by CSS Rules. If you use them right you can get rid off good amount of JavaScript code from your pages. You need to know the following properties to create and maintain CSS counters.
| counter-reset | Create or reset a counter |
| counter-increment | Increment a counter value |
| counter() or counters() | These functions inserts the counter value into a html element |
You can create a counter and increase its value using CSS rules. That's great but how is this going to help you. Let's look at the demo I have created in CodePen to explain CSS counters. In this demo, I create a grocery list and count each item with CSS counter function. Here is the HTML
Shopping List <div> <span>Tomatoes</span> <span>Parsley</span> <span data-item="Onion">Onion</span> <span>Garlic</span> <span>Olive Oil</span> </div>
Alright, now I am not going to throw bunch of CSS rules here and expect everybody to understand it. Let's do this step by step. First we need to create a counter, so I am going to write a CSS rule for the div element and create a counter named shoppinglist.
div{
counter-reset: shoppinglist;
padding: 10px;
}
We have the counter, now we can increase its value. Since all the grocery items are in a span element, we need to increase the value of shoppinglist counter in span level. I want to display the counter value right before the each span. I used the ::before selector to do that. Also I used the content rule to display the counter's value right before the span element.
div span::before{
counter-increment: shoppinglist;
content: counter(shoppinglist);
border: 1px solid black;
border-radius: 5px;
width: 40px;
padding: 3px;
background: black;
color: white;
margin: 0 2px 0 0;
}
This should take care of counters to display right front of each span. Next, I want to display the counter value when user hovers on a span.
div span:hover::after {
content: 'This is item ' counter(shoppinglist);
background: black;
padding: 5px;
color:white;
border-radius: 4px;
font-variant: small-caps;
position: absolute;
margin: 30px 0 0 0;
}
Just like ::before, ::after let us create a css rule after an html element. In this case, I am going to display text with the counter value in it. I made its position absolute to move its location so it will not appear right after the span's text. Also for some reason If you need to hide any of the spans, CSS counters will be refreshed. I have created a button which hides one of the items in the shopping list to demo refreshing. You can find the demo in my codepen account.

No comments:
Post a Comment