The other day we made an emoji list. And I wanted to include another potent CSS
property called CSS
Counters.
This is the result in Codepen.
See the Pen CSS custom numbered list styling by Chris Bongers (@rebelchris) on CodePen.
What are CSS Counters?
They are variables controlled by CSS
, whose values can increment by specific CSS
rules.
We can use the following properties in CSS
.
content
-> Used to place thecounter()
property.counter-reset
-> Creates or resets an countercounter-increment
-> Increment a specific countercounter()
-> Adds the value to an element
HTML Structure
Let’s create a straightforward example using two lists. We want each list to re-start the counter.
<div>
<ol>
<li>Item #1</li>
<li>Item #2</li>
<li>Item #3</li>
<li>Item #4</li>
<li>Item #5</li>
</ol>
</div>
<div>
<ol>
<li>Item #1</li>
<li>Item #2</li>
<li>Item #3</li>
<li>Item #4</li>
<li>Item #5</li>
</ol>
</div>
CSS counter styling
So how do we now use CSS
counters?
Let’s start with the <ol>
element.
ol {
counter-reset: custom;
list-style-type: none;
padding: 0;
margin: 0px 20px;
}
We start by resetting the list counter called custom
.
Then we remove the default list style since we will add this custom one.
Now we can move on to the <li>
styling.
ol li {
counter-increment: custom;
padding: 15px 0;
display: flex;
align-items: center;
}
Here we increment the custom counter and add some essential padding and alignment.
We need to use this counter in a before
pseudo element.
ol li:before {
content: counters(custom, '.') ' ';
width: 30px;
height: 30px;
margin-right: 10px;
background: purple;
color: #fff;
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
}
As you can see, we place our custom counter in the content element. We then added some basic styling to make it look slightly nicer.
I’m using many flex options to style everything centered.
Some outstanding examples
Now that you have seen my introduction check what these incredible people made with this fantastic CSS
property.
Check this cool gradient one made by Mattia Astorino
See the Pen CSS Gradient Counter List by Mattia Astorino (@equinusocio) on CodePen.
Or this section layout one made by Jonathan Snook
See the Pen Timeline CSS with Counters by Jonathan Snook (@snookca) on CodePen.
Or even this absurdly good Tic-Tac-Toe with counters by Sαwsαn
See the Pen Pure CSS & Responsive Tic-Tac-Toe (Modern Browser Only) by Sawsan (@saawsan) on CodePen.
Browser Support
And the good news?
CSS Counters are fully supported! 🎉
Thank you for reading, and let’s connect!
Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter