Quick Tip: How to Keep the Count with CSS

Did you know that, with CSS, you can create a counter? This can be especially useful for instances where the count is purely needed for presentational purposes. I'll show you how to use counter-increment in this useful quick tip.


Choose 720p for the best picture.

How Does it Work?

It's really quite simple. We're not even talking CSS3 here; the counter-increment property has been around for a while now. It's just that many of us aren't familiar with it, or haven't found a use for it.

We begin by applying the counter-increment property. Let's imagine that we have a set of boxes, and each box should display a number that corresponds to the order that the box occurs it its sequence.

The counter-increment property can accept either one or two properties. The first is an id that you will later use to reference this specific counter. You may also pass a second parameter that refers to the increment. For example, instead of 1, 2, 3, 4, you could switch to 5, 10, 15, 20 by applying: counter-increment: boxes 5.

This code will now store a unique number for each element that has a class of box. But of course, we want to get this number on the page. Hopefully, we'll, at some point in the future, be able to use the content property within standard selectors, but not quite yet. Instead, we'll use pseudo elements to apply the content.

This will apply a unique number - again, based on the element's order in the sequence - to the .box element. Should we need to reset this order back to 1 at some point, we could usethe counter-reset: boxes property.

Why Do This, Again?

Now, you still might be thinking: "Why would I ever use this?" There's lots of situations when it might be handy. For example, consider a comments section of a blog. If you wanted to provide
a number for each comment in the set - possibly slightly transparent - you could use this technique. The number isn't vital to the markup, and is only used for presentation. In these cases, CSS
counters will do the trick nicely!



Related Articles