πŸ’‘ This page contain affiliate links. By making a purchase through them, we may earn a commission at no extra cost to you.
How to Automatically Number Headings with CSS

How to Automatically Number Headings with CSS

Ferenc Almasi β€’ 2022 January 26 β€’ Read time 1 min read
  • twitter
  • facebook
CSS

To automatically number headings with CSS, we can use three CSS properties that are working as counters: counter-reset, counter-increment, and counter:

Copied to clipboard! Playground
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:

Copied to clipboard! Playground
<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
How to Automatically Number Headings with CSS
If you would like to see more Webtips, follow @flowforfrank

10 Best Practices for Quickly Improving Your CSS

Resources:

  • twitter
  • facebook
CSS
Did you find this page helpful?
πŸ“š More Webtips
Mentoring

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:

Courses

Recommended

This site uses cookies We use cookies to understand visitors and create a better experience for you. By clicking on "Accept", you accept its use. To find out more, please see our privacy policy.