To use this website fully, you first need to accept the use of cookies. By agreeing to the use of cookies you consent to the use of functional cookies. For more information read this page.

CSS 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

Initialisation

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

CSS
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.

Incrementing

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

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

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

Implementation

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:

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

Now given some HTML:

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

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.

Provide feedback on this page
Comments are sent via email to me.