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.
h2[id] { scroll-margin-top: 4rem; }
Try it
Syntax
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
autoor percentages, unlikescroll-padding. - Use
scroll-marginon the target, andscroll-paddingon the scroll container. If every target needs the same gap, the container-levelscroll-padding-topis 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
remor 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.
Related
scroll-paddingโ offset set on the scroll containerscroll-snap-alignโ which edge of the area snapsscroll-behaviorโ smooth jumps- Lesson: Scroll Snap