DEV Community

Andrei Valentin Popa
Andrei Valentin Popa

Posted on

Offsetting anchors to adjust for a fixed header.

So, you got your nice little sticky header, it looks good but any #to-my-title or #to-my-reference bits are linking to areas that are covered by the header.

This is a common problem that is a bit difficult to solve but here is how I did it in my Astro project.

/* Offsetting anchor to adjust for fixed header */
a[aria-describedby="footnote-label"]:target {
    padding-top: 50% !important;
}

h1[id]:before,
h2[id]:before,
h3[id]:before,
h4[id]:before,
h5[id]:before,
h6[id]:before {
    display: block;
    content: " ";
    margin-top: -75px;
    height: 75px;
    visibility: hidden;
}
Enter fullscreen mode Exit fullscreen mode

This code might look complicated, that's because it is.

The first rule applies to any link (a) that has an attribute aria-described by with the value footnote-label and is the target of the current URL (meaning it has a hash fragment that matches its id). This rule adds a 50% padding-top to the link, which means it will place it in the middle of the screen.

The second rule applies to any heading that has an id attribute. This rule adds a pseudo-element (:before) to the heading, which is an invisible element that is inserted before the heading’s content. This pseudo-element has a height of 75px and a negative margin-top of 75px, which means it will occupy the same space as the heading but will not affect its position or layout, placing the "target" of the link actually a little bit above the actual heading.

Top comments (0)