smhk

Hugo anchors next to headers

This note documents how to add anchors to your headings in hugo, which show up only upon hover.

Example h2 heading §

Example h3 heading §

Example h4 heading §

Example h5 heading §

These headings are an example of the anchor in action. Hover over them and an anchor will show up to the right, which can be clicked on.

Code §

First, add a hugo partial named headline-hash. This uses a regular expression to append an <a href ... /> after each <h[1-5] /> tag. Create the following file:

layouts/partials/headline-hash.html
{{ . | replaceRE "(<h[1-5] id=\"([^\"]+)\".+)(</h[1-5]+>)" `${1}&nbsp;<a href="#${2}" class="headline-hash" ariaLabel="Anchor">§</a> ${3}` | safeHTML }}

Then, update your layouts to use the partial on whatever .Content it should apply to. For example, in my case the only place I needed to put it was in single.html:

layouts/_default/single.html
<!-- ...snip.. -->
{{ partial "headline-hash.html" .Content }}
<!-- ...snip.. -->

Finally, update your CSS so that the headline-hash class is hidden by default, but shows when the mouse hovers over the heading:

stylesheet.css
/* ...snip... */

.headline-hash {
    visibility: hidden;
}

h1:hover a,
h2:hover a,
h3:hover a,
h4:hover a,
h5:hover a {
    visibility: visible;
}

/* ...snip... */

Credit §

Full credit goes to kaushalmodi who shared this gist.

Future improvements §

As suggested by sephore, it may be possible to use markdown render hooks instead of replaceRE.