Prevent content from being hidden underneath a fixed header by using `scroll-margin-top`

If you’ve ever implemented a design with a fixed header, you’ve surely had this problem:

You click a jump link like <a href="#header-3">Jump</a> which links to something like <h3 id="header-3">Header</h3>. That's totally fine, until you have a position: fixed; header at the top of the page obscuring the h3 you're trying to link to!

Fixed headers have a nasty habit of hiding the element you’re trying to link to.

Thankfully Chris Coyier from CSS-Tricks found and shared the straightforward solution:

h3 {
  scroll-margin-top: 5rem; /* whatever is a nice number that gets you past the header */
}

To not have to apply the CSS rule to too many elements, I’d adjust the snippet to use the :target selector.

The :target CSS pseudo-class represents a unique element (the target element) with an id matching the URL’s fragment.

That way it will work with any internally linked thing (headers in all their sizes, anchors, etc):

:target {
  scroll-margin-top: 5rem;
}

It was also nice to see that Mattias Geniar used this solution when implementing the Smooth Scrolling Sticky Navigation I wrote about earlier (Mattias is using scroll-padding-top though).

Fixed Headers and Jump Links? The solution is scroll-margin-top

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.