Sticky Header Covering Anchor Headings? Fix It with One CSS Property: scroll-margin-topBrief · digest for November 21
Brief≈ 1 min

Sticky Header Covering Anchor Headings? Fix It with One CSS Property: scroll-margin-top

You click "Shipping" in a table of contents, the page scrolls down, and the heading hides right behind the sticky header. Developers used to patch this with invisible <span> tags, negative margin-top hacks, or JavaScript listeners. Now all you need is scroll-margin-top—an invisible top buffer that only kicks in during anchor jumps or scrollIntoView() calls:

<!-- Anchor link and target heading -->
<a href="#delivery">Shipping</a>
<h2 id="delivery">Shipping Terms</h2>

Apply the offset to the heading. To match a slimmer header on mobile, store the height in a CSS custom property:

/* Header height on desktop and mobile */
:root {
  --header-height: 5rem;
}

@media (max-width: 768px) {
  :root {
    --header-height: 3.5rem;
  }
}

/* Top buffer when scrolling to the anchor */
#delivery {
  scroll-margin-top: var(--header-height);
}

Scrolling stops cleanly below the header without messing up normal layout spacing. The property has been Baseline (Widely available) since April 2021 and works in all modern browsers. If you want one rule for every anchor on the page, set scroll-padding-top: var(--header-height) on html. Just remember to update the variable if your header height changes dynamically.

Want a deep diveVotes help us choose what to break down in detail. This material has 0 votes.
Sources · 2