You may want to number elements on a page that do not technically form a list. For example, the tutorials on the stylus blog are always broken up into a sequence. Each step in the sequence is announced with a heading level 2 element, <h2>. To save myself the hassle of numbering them manually, I have used some CSS to automate the numbering.
In this tutorial:
Required knowledge:
Some HTML
Nothing fancy here at all:
<h1>Automatically numbering elements with CSS</h1> <h2>The first step in the tutorial</h2> <p>A whole lot of super-useful instructions with useful information.</p> <h2>The second step in the tutorial</h2> <p>With a whole lot more super-useful instructions and useful information.</p>
Some CSS
There are two important concepts involved in this example: the first is the counter function, and the second the ::before pseudo-selector.
counter function
The counter function allows the creation of a variable for counting. It is reset using the body selector. It can be incremented using counter-increment , and the current value can be output using counter().
::before pseudo-element
The ::before pseudo-element enables the insertion of content before an element. In our example, we output (prepend) the value of the counter named stepcounter concatenated with a full stop and a space. \00A0 is Unicode.
body {
counter-reset: stepcounter;
}
h2 {
counter-increment: stepcounter;
}
h2::before {
content: counter(stepcounter) ".\00A0";
}
A Codepen
Hop on over to the Codepen and play around:
See the Pen Untitled by David Fox (@foxbeefly) on CodePen.
Final product
The screenshots below illustrate the “steps” of the tutorial. The headings are HTML <h2> elements automatically numbered in CSS. CSS box shadows, rounded corners and a hover state add to the visual idea of separate steps.


References:
- W3Schools Online Web Tutorials, W3Schools.com (no date) CSS ::before Pseudo-element. Available at: https://www.w3schools.com/cssref/sel_before.php (Accessed: 9 November 2024).
- W3Schools.com (no date) CSS counter() function. Available at: https://www.w3schools.com/cssref/func_counter.php (Accessed: 9 November 2024).