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:
What we will achieve is to automatically show them as:
CSS countersTo obtain the above goal we are going to use CSS and specifically counters. Generally speaking:
Counter-increment increments the value of a counter by a specific value (default is 1, if not given).
tags, representing our chapters. We are going to manipulate those tags, using the content property and the :before pseudo-element.
Imagine we get chapters from our database, and list them like:
chapter 1and so on...
chapter 2
chapter 3
What we will achieve is to automatically show them as:
1. chapter 1Isn't it nice? Let's see how we can do it.
2. chapter 2
3. chapter 3
CSS counters
"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 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 tag:
h2 {
counter-increment: chapter;
}
That will increment our counter.
Finally we need to display the counter just before every tag:
h2:before {
content: counter(chapter) ". ";
}
And that is all.
body {
counter-reset: chapter;
}
h2 {
counter-increment: chapter;
}
That will increment our counter.Finally we need to display the counter just before every
tag:
h2:before {
content: counter(chapter) ". ";
}
And that is all.
h2:before {
content: counter(chapter) ". ";
}