How do you offset an anchor link so it is positioned below a fixed header?

  • Page Owner: Not Set
  • Last Reviewed: 2019-12-16

Out of the box, following an on-page anchor link jumps the target location to the very top of the browser window. If there is a fixed or sticky header, that content ends up hidden under the navbar. Is there an elegant solution to slide this down from under the fixed header?


Answer

Update: CSS scroll-padding takes all the pain and suffering out of this issue. The syntax is the same as regular padding on an element. You can add scroll-padding on the top, right, bottom, or left side of an element to create an offset or safe zone for overlapping elements. For example, this would give you a 50px gap at the top for a sticky nav.

.scroll-container {
  scroll-padding: 50px 0 0 0;
}

This approach adapts the scroll position rather than trying to fix specific scroll anchor behavior, so it is more reliable and solves more issues than what was previously possible.


Old hacky approach: I have used this solution in the past. It works well if the anchor ID is on a text element.

:target:before {
   content:"";
   display:block;
   height:90px; /* fixed header height*/
   margin:-90px 0 0; /* negative fixed header height */
}

Note: This doesn't work if the anchor ID is on a DIV. It also doesn't handle positioning of the page if the user is tabbing through a form or using a screen reader.

But for "back to top" links or other true anchor jumps, this works great!