How to Automatically Number Headings with CSS
To automatically number headings with CSS, we can use three CSS properties that are working as counters: counter-reset
, counter-increment
, and counter
:
body {
counter-reset: heading;
}
h1:before {
content: counter(heading) ") ";
counter-increment: heading;
}
This code will first create a new counter called heading
, with a default value of 0. To create counters in CSS, we can use counter-reset
. Then to use it for headings, we can use the ::before
pseudo-element and reference the counter
we have created, using the counter function. Make sure you also call counter-increment
, this will increment the counter by one for every element. This will generate the following:
<h1>Table of Contents</h1>
<h1>The Tale of CSS</h1>
<h1>Acknowledgments</h1>
<!-- Will be rendered as: -->
1) Table of Contents
2) The Tale of CSS
3) Acknowledgments
Resources:
Rocket Launch Your Career
Speed up your learning progress with our mentorship program. Join as a mentee to unlock the full potential of Webtips and get a personalized learning experience by experts to master the following frontend technologies: