Friday, 21 October 2011

CSS: automatic chapter numbering with counters


If your web page is divided in chapters fetched from a database, you can automatically number those chapters, using CSS counters. The solution is very useful in situation where the numbering is in some way dynamic.

Imagine we get chapters from our database, and list them like:
chapter 1
chapter 2
chapter 3
and so on...
What we will achieve is to automatically show them as:
1. chapter 1
2. chapter 2
3. chapter 3
Isn't it nice? Let's see how we can do it.

CSS counters
To obtain the above goal we are going to use CSS and specifically counters. Generally speaking:
"CSS counters are an implementation of Automatic counters and numbering in CSS 2.1. The value of a counter is manipulated through the use of counter-reset and counter-increment and is displayed on a page using the counter() or counters() function of the content property." (quoted from MDN)
Counter-reset is used to reset the counter to a specific value (default is 0, if not given).
Counter-increment increments the value of a counter  by a specific value (default is 1, if not given).

How do we implement it?
It's not that complicated. We assume we have a series of <h2> tags, representing our chapters. We are going to manipulate those tags, using the content property and the :before pseudo-element.

First of all, we need to reset the counter:
body {
    counter-reset: chapter;
The name of our counter is set to "chapter".
After that, we decide to increment the counter on every <h2> tag:
h2 {
    counter-increment: chapter;
That will increment our counter.
Finally we need to display the counter just before every <h2> tag:
h2:before {
    content: counter(chapter) ". ";
And that is all.

0 thoughts:

Post a Comment

Comments are moderated. I apologize if I don't publish comments immediately.

However, I do answer to all the comments.