Categories
SEO

Automatic heading numbering with CSS

To implement automatic heading numbering with CSS, you can use the CSS counters feature where:

<h2>Heading 1</h2>

<h2>Heading 2</h2>

<h3>Sub-heading</h3>

automatically becomes:

1. Heading 1

2. Heading 2
2.1. Sub-heading

CSS counters let you increment a number each time an element appears in the document.

Here’s a basic example of how you can achieve automatic heading numbering for h2, and h3 tags in a hierarchical structure, similar to sections and subsections in a document:

body {

counter-reset: section; /* Initializes a counter named ‘section’ for the body element */

}
h2 {
counter-reset: subsection; /* Each h2 element resets the subsection counter */
counter-increment: section; /* Increment the section counter for each h2 */
}
h2:before {
content: counter(section) “. “; /* Display the section counter before h2 content */
}
h3 {
counter-increment: subsection; /* Increment the subsection counter for each h3 */
}
h3:before {
content: counter(section) “.” counter(subsection) ” “; /* Display section.subsection before h3 content */
}

The above adds the pseudo-element :before. Everything within :before is just a visual representation but not actual content of the document. (Similar to dots in lists.)

As for SEO, these kind of methods are better because you don’t add additional characters to the headings. Adding  numbering as real characters could potentially confuse search engines.

For example, numbering with actual text

2.2 Centimeters in Inches

would suggest that you are talking about how many inches 2.2 centimeters is.

While with CSS-method above

2.2 Centimeters in Inches

since 2.2 is not part of the text, the interpretation is that it’s about the relation between centimeters and inches in general.