Également disponible en : Français
As I told you, the counters exist and are defined since CSS2.1 by the W3C. The arrival of CSS3 allowed to complete the definition a bit and to include it in a module called “Generated and Replaced Content“.
In this article, we will play with three properties and one function:
counter-reset: this property allows you to initialize a counter (create it). To do this, you need to fill in one or more counter names followed by its initial numerical value.
Here we’ve got two initialized counters:
count1which starts at 4, and
count2which starts at 0.
counter-set: this property allows you to redefine the value of a counter, without creating a new one. To do this, fill in one or more existing counter names followed by its new numerical value.
Here we have two counters redefined:
count1which restarts at 0, and
count2which restarts at 3.
counter-increment: this property allows you to increment a counter. To do this, enter the name of one or more counters, each followed by the number to be incremented. Without number following the counter name, the increment will be +1 by default.
Here our two initial counters will be increased by 2 for count1 and 4 for count2.
counter(): this function associated with the pseudo-element
contentproperty allows you to insert the counter in your page. This generates a dynamic content. It takes one parameter and a second optional parameter. The first one is the counter name, the second one is the counter style. (same values as
In this example, the content of a
lielement will be preceded by a content type of “04 -“.
Counter CSS Démo
The simplest way to present those CSS Counters is to give you a well-organized document with a few headings at different levels.
Here is the demonstration:
CSS Counters Demo
The code used in HTML is relatively simple: make sure you have
h4 in a block of text, for example. I give you a snippet if you want to test :
The CSS is relatively short when it comes to counters, you just have to pay attention to the details: when counters are initiated and incremented.
CSS Counters demo on an odered list
You’re going to tell me: What’s the point since the
ol list is already numbered?
Yes, that’s true, but the use of the generated content allows to apply richer styles thanks to CSS.
An example in image (and code):
There is a lot of stuff to know about lists, especially
ol elements. Discover more about attribute start, reversed and type of counters.
Don’t hesitate if you have any question.
Post a comment for this article?
Follow comments and trackbacks