HTML5 and CSS3 Advent 2011

Counting on counter() and friends

The good old <ol> has been around a long time for creating numbered lists, but it has always been rather limited in its use. In CSS2.1 generated content has been added to the spec. With generated content you can define counters and add them (together with other content) to any element with the :before and :after pseudo-elements. So, today's entry isn't that cutting-edge, but as browser support has been lacking (we're looking at you IE!) it's not something you see in a lot of websites.

You could make a battleship-board with it... (hover over the board with your mouse)

This a new chapter

Some intro text

An article

The chapter consists of several articles

Another article

The string "article X.X" is automatically generated from the CSS

And another chapter

It's all quite simple

Bla bla bla

Counters can also be used for proper documents.

Todolist

Check the items off the list.

  • Buy presents
  • Do groceries
  • Study CSS counters

You still need to do things.

Thanks to counter(), this count-down interactive todolist uses no javascript at all.

How does it work?

Basically there are three things we need to specify to make counters work: we have to set a counter-reset: countername, a counter-increment: countername and we have to place the counter with content: counter(countername). With counter-reset: countername 1 we reset the counter "countername" to value 1 (which is the default so it can be omitted). With counter-increment: countername 1 we increment the counter by one (the amount is optional and defaults to one). To place the counter we use a :before or :after pseudo-element with content: counter(countername, decimal). As you see we use a decimal counter here, but this could be any valid list-style-type.

A more advanced topic is the counters() function which makes working with nested lists a breeze. We're not going to cover that here, but this article on the Mozilla Developer Network explains how counters work.

Show us the source!

Feel free to look around the different source files we used for this example.

Check out our all new HTML & CSS Advent 2012