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 */
}

🐛 As noted in the comments below this doesn’t work Safari. All other modern browsers do have excellent support for scroll-margin-top and play nice.

~

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

~

Did this help you out? Like what you see?
Thank me with a coffee.

I don't do this for profit but a small one-time donation would always put a smile on my face. Thanks!

☕️ Buy me a Coffee (€3)

Published by Bramus!

Bramus is a Freelance Web Developer from Belgium. From the moment he discovered view-source at the age of 14 (way back in 1997), he fell in love with the web and has been tinkering with it ever since (more …)

Join the Conversation

1 Comment

Leave a comment

Leave a Reply to Steffen Cancel reply

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.