Jamie Balfour

Welcome to my personal website.

Find out more about me, my personal projects, reviews, courses and much more here.

Part 8.3CSS counters

Part 8.3CSS counters

One of the most useful new features in CSS is the addition of counters.

What counters are

Counters are, simply put, a way of counting what number the element is. These counters can be retrieved and used as content is CSS. HTML already defines an element with counters on it - the ol element.

On this website, code samples and the article navigation links are used with counters instead of the default numbers given by the ol element. This means that they can be styled as needed rather than being just the standard numbers.

CSS counters

Counters require three things:

  • Initialisation
  • Incrementing
  • Implementation


A counter is initialised to start with, so for this example, the div.counted is being used:

div.counted {
	counter-reset: count;

This will mean that for ever div.counted that the browser sees, the counter, count, will be reset to 0 again.


The next step is to increment the children of div.counted on each child:

div.counted > * {
	counter-increment: count;

Using the child selector, the browser will increment the value of count for each child of div.counted.


The third and final step when using counters is the implementation - after all there would be no point to them if they could not be used.

Using the pseudo-selectors :before and :after as well as the content property allows the use of counters in the content:

div.counted > *:before {
	font-weight: bold;
	color: purple;
	content: "Number " counter(count) ": ";

Now given some HTML:

<div class="counted">
	<p>Hello world</p>
	<p>HTML is fun</p>

Hello world

HTML is fun

This can be used to style list numbers, but due to the lack of support in older browsers, is not fully recommended.

Feedback 👍
Comments are sent via email to me.