Shreyas Jani

I'm a web designer & software engineer based out of Mumbai.

I write about technology & love documenting the world around me through photography.

Generating a list of numbers in CSS using pseudo selectors

CSS IS AWESOME.

There, I just said it. HAHA.

At my internship with Coverfox, I was tasked with building an Emailer that had 3 steps outlined in it. It looked something like this:

The way I saw it, I wanted to build a list and then use list-style-type: decimal; to get the numbers. But at the time, I had no clue how to style it. I don't know how to style it now as well. And so I put the numbers in a :before pseudo selector and then in the :after pseudo selector, I added the background color and got what was needed.


......
.list {
 list-style: none;
 padding: 22px;
}


.list:before {
 padding: 5px 12px;
 background-color: #FF704C;
 border-radius: 50%;
 color: #fff;
 font-size: 22px;
 margin-right: 18px;
}

 
.one:before {
 content: "1";
}
 
 
.two:before {
 content: "2";
}
 
 
.three:before {
 content: "3";
}
.....
 

Now that I look at it, it was a bad way to achieve the result. If you want to add a list of 100 numbers, you'd have to add 100 unique classes and repeat the CSS 100 times. Talk about keeping things DRY.

CSS has this handy propery called counter-reset and counter-increment. This property will generate numbers for us that can then be used in the content. One property to generate limitless numbers using CSS. Sounds great right?

counter-reset[0] resets a CSS counter to a given value while counter-increment[1] increases or decreases the value of a CSS counter by a given value.

The following will be my markup:

<ul class="wrapper"> <li class="counter"> Content One </li> <li class="counter"> Content Two </li> <li class="counter"> Content Three </li> </ul>

Using this css, we can generate a list of numbers.

 
.wrapper {
 display: flex;
 justify-content: center;
 align-items: center;
 counter-reset: number;
}
.counter {
 counter-increment: number;
 text-align: center;
 position: relative;
 margin: 0 12px;
}
.counter:before {
 content: counter(number)" ";
 color: #000000;
}
.counter:after {
 content: "";
 
 // background styles can be
 // written here to add a
 // background color to
 // the numbers.

}
 

This way, we can add any number of list items in the markup without having to worry about writing extra css.

MDN Links: [0] counter-reset [1] counter-increment