Hugo anchors next to headers
All notes in this series:
- (1) Automating hugo development with npm scripts
- (2) normalize-scss with hugo
- (3) Automatic image thumbnails in Hugo from static directory
- (4) Escaping Hugo shortcodes within Hugo markdown
- (5) Hugo tag and category pages
- (6) Bind hugo to localhost for development
- (7) Hugo 0.37 does not support h6 markdown heading
- (8) Install Hugo testing distribution on Debian
- (9) Hugo anchors next to headers
- (10) Hugo: Migrating from Pygments to Chroma
- (11) Hugo: Global resources
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 §
On this site, the h5 heading is used especially for code blocks.
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} <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.. -->
stylesheet.css §
Finally, update your CSS so that the headline-hash
class is hidden by default, but shows when the mouse hovers over the heading:
/* ...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
.