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

Avatar of Chris Coyier
Chris Coyier on

AWS Amplify - the fastest, easiest way to develop mobile and web apps that scale.

The 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 header you’re trying to link to!

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

There used to be all kinds of wild hacks to get around this problem. In fact, in the design of CSS-Tricks as I write, I was like, “Screw it, I’ll just have a big generous padding-top on my in-article headers because I don’t mind that look anyway.”

But there is actually a really straightforward way of handling this in CSS now.

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

We have an Almanac article on it, which includes browser support, which is essentially everywhere. It’s often talked about in conjunction with scroll snapping, but I find this use case even more practical.

Here’s a simple demo:

In a related vein, that weird (but cool) “text fragments” link that Chrome shipped takes you to the middle of the page instead, which I think is nice.