Skip to content
Tutorials Center
My learning

Topics

CSS Reference ยท Scrolling, Interaction and UI

The scroll-margin property

Reference for the CSS scroll-margin shorthand and its longhands: keep snap areas and scrollIntoView targets clear of fixed headers, with a live example.

The scroll-margin property adds an outset around an element's snap area. When the browser scrolls that element into view, for instance after clicking a #fragment link, calling scrollIntoView(), or snapping, it aligns the margin box instead of the border box.

It is the usual fix for anchor targets that hide under a fixed header: give each target a scroll-margin-top the height of the header. The margin is invisible and does not change layout.

CSS
h2[id] {
  scroll-margin-top: 4rem;
}

Try it

Target stays below the sticky bar

Syntax

CSS
scroll-margin: <length>{1,4};
scroll-margin-top | -right | -bottom | -left: <length>;
scroll-margin-block | scroll-margin-inline: <length>{1,2};
scroll-margin-block-start | -block-end | -inline-start | -inline-end: <length>;
  • Initial value: 0
  • Applies to: all elements
  • Inherited: no
  • Animatable: yes, as a length
  • Computed value: absolute lengths

Values

Value Description
<length> An outset from the border edge, for example 4rem or 80px. Negative values shrink the snap area.
1 to 4 values Follow the same order as margin: top, right, bottom, left, with the usual shorthand repetition rules.

Usage notes

  • It does not accept auto or percentages, unlike scroll-padding.
  • Use scroll-margin on the target, and scroll-padding on the scroll container. If every target needs the same gap, the container-level scroll-padding-top is shorter to write.
  • The effect applies to scroll snapping, to fragment navigation and to scrollIntoView() alike.
  • Because it is not layout margin, it never pushes neighboring content around.
  • Use rem or a custom property that matches your header height so the two stay in sync when the design changes.

Browser support

Supported in all current browsers.