All writing
3 min read

Stop Anchor Links Hiding Behind Your Fixed Header

Sticky navbar eating the top of every section you jump to? One CSS property fixes it properly — no padding hacks, no JavaScript.

CSSFrontend

Here is a bug almost every site hits. You build a page with a navbar that links to sections lower down — #about, #work, #contact — using IDs. Click a link, the page scrolls to that section. Lovely.

Then you make the navbar position: fixed. Now when you jump to a section, the fixed navbar covers the top of it: the browser scrolls the anchor to the very top of the viewport, exactly where the header is sitting, so the heading hides behind it.

The hack everyone reaches for

The usual fix is to pad every section by the header's height with padding-block, or add an invisible offset element. It works, but it pollutes your layout with spacing that only exists to compensate for scrolling.

The actual fix

There is a property built for exactly this: scroll-margin-block. Set it a little larger than the navbar's height and the browser leaves that much room whenever it scrolls an element into view.

css
section[id] {
  scroll-margin-block: 6rem; /* a touch more than the header height */
}

That is it. No layout padding, no scroll listeners in JavaScript, no magic numbers sprinkled across components. The anchor lands below the header every time.

Browser support is excellent — you can use it today without a second thought. I keep a tiny demo repo for it at github.com/fadyehabamer/scroll-margin-block.


Written by Fady Ehab Amer

Get in touch →

Keep reading