Ever wondered how to automatically number your headings and subsequent paragraphs, and then reset those numbers for the next set? Well, wonder no more! Let’s explore how to achieve this using CSS counters. I’ve used this approach for the terms of business page on this website. Maybe you’ll have a similar use for it, too.
Why Might This Be Useful?
Imagine you’re crafting a documentation page, a tutorial, or any content where sections and their subsections need to be clearly numbered for easy reference. Manually numbering can be tedious, brittle, and if you decide to add or remove a section, you’d have to renumber everything. ARRRRRG. That’s where this CSS trick comes into play. It automates the numbering process, making your life a tad easier and your content more dynamic.
The Magic of CSS Counters
CSS counters aren’t new, but they’re somewhat underutilised. They allow you to automatically number elements, like list items or headings, without having to manually type in each number.
Here’s how we can set it up:
Initialise the Counter
First, we set up a counter on a parent element. If your H3 tags are direct children of the Body, then that’s where you’d set it.
body {
counter-reset: h3counter;
}
Number the Headings
For each H3 heading, we’ll increment our counter and display its value.
h3 {
counter-increment: h3counter;
counter-reset: pcounter; /* This ensures our paragraph numbers reset for each new heading */
}
h3::before {
content: counter(h3counter) ". ";
}
Number the Paragraphs
For the paragraphs following our headings, we’ll have a nested counter. This allows us to create a “sub-numbering” system.
p::before {
counter-increment: pcounter;
content: counter(h3counter) "." counter(pcounter) " ";
}
With this setup, your content will be automatically numbered like:
1. H3 Heading
1.1 Paragraph
1.2 Paragraph
2. Another H3 Heading
2.1 Paragraph
2.2 Paragraph
...
Wrapping Up
CSS counters offer a dynamic way to number content, making it easier to manage and adjust large chunks of text. Whether you’re crafting a user manual, a step-by-step guide, or just want to add a touch of structure to your blog posts, this method is a bit of a game-changer.