Numbered headings made with CSS counter
Adding numbers to headings will emphasize page structure and provide additional cues for users while navigating your web page.
You can add numbers to your headings with pure CSS. It won’t require any additional markup or JavaScript.
It can be done by implementing a CSS counters concept.
Say you have a following headings structure:
HTML:
<h1>Article Title</h1>
<h2>Introduction</h2>
<h2>Main part</h2>
<h3>Details</h3>
<h3>More details</h3>
<h2>Conclusion</h2>
You can make it look like this:
Adding CSS counters for headings
In CSS you’ll need to specify the counter-reset
property on the body
tag to start a new counter for the whole page. The value of this property is a variable that should be unique to be used by the specific heading level e.g. h2
headings.
body {
counter-reset: headings2;
}
To display the numeric value next to a heading, a ::before
pseudo-element is used. Its content
property should be equal to the counter()
function, which accepts the same variable we used for the counter-reset
property.
You can add a dot to a number, to separate it from heading text. To do so add a dot with a space as a string ". "
next to counter()
function.
Finally lets add a counter-increment
property and set its value to the same heading variable. As the name states it will increment counter value for the next heading.
h2::before {
content: counter(headings2) ". ";
counter-increment: headings2;
}
Adding counters for nested headings
Same logic can be applied for the next level of headings h3
and so on, up to h6
.
First we need to reset the counter on the parent heading, in this case h2
.
h2 {
counter-reset: headings3;
}
For the pseudo-element we need to set the content
equal to heading2
counter + heading3
counter with a dot separator. This structure will indicate the belonging to the parent heading section.
h3:before {
content: counter(headings2) "." counter(headings3) ". ";
counter-increment: headings3;
}
Prevent counters for specific headings
To prevent a number on a heading we can stop counters by setting a none
value for content
and counter-increment
properties of a headings’ pseudo-element.
Add a class name for those headings you wish to prevent numbers. And in CSS add following:
.non-numbered:before {
content: none;
counter-increment: none;
}
This is useful when you want to show regular headings after ending a list of numbered sections.
Final result
See the live example and a complete code on CodePen:
See the Pen Untitled by Nikita Hlopov (@nikitahl) on CodePen.