Auto number Headings & TOC in Hugo Pages Auto number Headings & TOC in Hugo Pages

Page content

In this tutorial, we’ll learn how to generate auto-numbering for headings, subheadings, and TOC in Hugo Pages.


When you generate a website using Hugo static site generator, It doesn’t provide any out of the box auto-numbering support for headings, subheadings, and TOC in Hugo Pages.

This blog website is also generated using Hugo and with few changes, we’re able to add auto-numbering support to our Hugo Pages.

If you’re still not clear what is auto-numbering all about then look at the auto incrementing numbers before the headings, subheadings and TOC in this post i.e. 1, 2, 2.1, 2.2, 2.3 etc.

1. Overview
2. Auto-numbering Pages
    2.1. Add “autonumbering” property in front-matter
    2.2. Add CSS Class to single.html
    2.3. Add CSS Styles to style.css

Let’s discuss how to enable this feature.

Auto-numbering Pages

Follow these three steps to enable auto-numbering feature in your Hugo website:

Add “autonumbering” property in front-matter

First of all, we’re going to add a custom property autonumbering in the front-matter of our Hugo pages.

We can enable or disable auto-numbering for a specific page using this property. If autonumbering: true, means it is enabled otherwise disabled.



autonumbering: true

Add CSS Class to single.html

Next, we are going to edit layouts/_default/single.html file and add a condition on article element to add autonumbering CSS class based on autonumbering property is enabled or disabled.

Please note that if you are using any Hugo theme then you can find single.html in themes folder.

{{ define "main" }}
  <article class="post" {{- if .Param "autonumbering" }} autonumbering {{- end }}>
{{ end }}

If autonumbering is enabled on any post. It will look like this:

  <article class = "post autonumbering" ></article>

If autonumbering is disabled on any post. It will look like this:

  <article class = "post" ></article>

Add CSS Styles to style.css

At last, add the following CSS Styles snippet in the CSS files you would be using in your project. Location of css file may differ in your project.

/* Auto Numbering */
body {counter-reset: h2}
h2 {counter-reset: h3}
h3 {counter-reset: h4}
h4 {counter-reset: h5}

article[autonumbering] h2:before {counter-increment: h2; content: counter(h2) ". "}
article[autonumbering] h3:before {counter-increment: h3; content: counter(h2) "." counter(h3) ". "}
article[autonumbering] h4:before {counter-increment: h4; content: counter(h2) "." counter(h3) "." counter(h4) ". "}

article[autonumbering] .toc__menu ul { counter-reset: item }
article[autonumbering] .toc__menu li a:before { content: counters(item, ".") ". "; counter-increment: item }

That’s it. You should be able to use autonumbering feature in your hugo pages now.