Adding anchor next to headers

Here’s what I ended up with in my single.html layout:

    {{- with .Content -}}
    <div>
      {{ . | replaceRE "(<h[1-9] id=\"([^\"]+)\".+)(</h[1-9]+>)" `${1}<a href="#${2}" class="hanchor" ariaLabel="Anchor"> 🔗&#xFE0E;</a> ${3}` | safeHTML }}
    </div>
    {{- end -}}

The CSS needed (I only show anchors on headings 1-4) is:

.hanchor { font-size: 100%; visibility: hidden; color:silver;}
h1:hover a, h2:hover a, h3:hover a, h4:hover a { visibility: visible}

The anchor shows in silver when you move the mouse over the heading and turns black when you hover over the anchor itself.

Also note the ariaLabel which you should really include for accessibility.

11 Likes