Counters

Back to the index.

See the specification.

On this page I test the CSS counter declarations.

Using the CSS counter syntax you can define as many counters as you like in your page, increment and reset them.

Showing a counter

In order to use a counter, you should give it a name. In this page I create three counters: section and subsection for use with the headers, and example for use with the <pre>s.

h3:before {
	content: counter(section) ": ";
}

h4:before {
	content: counter(section) "." counter(subsection) ": ";
}

Now all <h3>s and <h4>s are preceded by their section and subsection numbers.

The syntax for showing the counter name is counter(counterName). The element:before pseudo-element is the most obvious choice for showing the counter, but element:after is also allowed.

Non-decimal counters

By default, counters use decimal numbers. However, you can use any value that's also a valid value for list-style-type (though the unordered ones don't make much sense). For instance, I count the <pre>s in this document by Greek letters:

pre:before {
	content: "(ex " counter(example,lower-greek) ")";
}

The syntax is (counterName,list-style-type value).

Incrementing a counter

Incrementing a counter is done through the counter-increment declaration. For instance, I increment the example counter with each <pre> in the document:

pre {
	counter-increment: example;
}

Incrementing by another value than 1

The default increment is 1; if you want to increment it by another value, use a space and then the desired value. For instance:

pre {
	counter-increment: example 3;
}

Now the example counter is incremented by 3 for every <pre> encountered.

Resetting a counter

Finally, the counter-reset declaration allows you to reset a counter. I do that with the subsection counter; it should reset to 0 for every <h3> encountered.

h3 {
	counter-increment: section;
	counter-reset: subsection;
}

h4 {
	counter-increment: subsection;
}

Resetting to another value than 0

Resetting to another value than 0 requires you to state the value:

h3 {
	counter-reset: subsection 4;
}

Now the counter is reset to 4.