scroll-margin
is part of the CSS Scroll Snap Module. Scroll snapping refers to “locking” the position of the viewport to specific elements on the page as the window (or a scrollable container) is scrolled. Think of a scroll-snapping container like putting a magnet on top of an element that sticks to the top of the viewport and forces the page to stop scrolling right there.
scroll-margin
is an optional property for a scroll-snapping element within a scroll-snapping container. For more information on scroll-snapping containers see the scroll-snap-type
almanac entry.
Enter scroll-margin
scroll-margin
is used to adjust an element’s snap area (the box that defines where the element will be snapped to). Adding scroll-margin
is useful when you need to give an element space from the edge of the container when snapped into place, but allowing for situations where each element might need slightly different spacing. If all elements have the same spacing requirements, consider using scroll-padding
on the parent container instead of scroll-margin
because that affects spacing for all elements within the container.
A simple example where the scroll-margin
allows for 50px spacing around the top and left of an element looks like this:
.scroll-element {
scroll-margin: 50px 0 0 50px;
}
![](png/screen-shot-2019-02-11-at-3.36.52-pmdbcb.png)
scroll-margin
on this element.Syntax
/* Shorthand */
scroll-margin: <length>{1,4};
/* Longhands */
scroll-margin-top: <length>;
scroll-margin-right: <length>;
scroll-margin-bottom: <length>;
scroll-margin-left: <length>;
/* inline-specific and block-specific properties as well */
scroll-margin-block: <length>{1,2};
scroll-margin-inline: <length>{1,2};
Important note on longhands: Chrome (and possibly other browsers) do not currently support longhand-format scroll-padding
and scroll-margin
properties. Use the shorthand for maximum browser support. See this issue on the chromium bug tracker for more details and current status.
Values
scroll-margin
accepts the following a length <length>
value, which is written similar to margin
and other properties where the value can be defined with units (px
, em
, vh
, etc). See the W3C Values and Units Module for more information. Percentages cannot be used for scroll-margin
per the spec.
Example
See the Pen scroll-padding example
by CSS-Tricks (@css-tricks) on CodePen.
Browser Support
This browser support data is from Caniuse, which has more detail. A number indicates that browser supports the feature at that version and up.
Desktop
Chrome | Firefox | IE | Edge | Safari |
---|---|---|---|---|
69 | 68 | 11* | 79 | 11 |
Mobile / Tablet
Android Chrome | Android Firefox | Android | iOS Safari |
---|---|---|---|
123 | 124 | 123 | 11.0-11.2 |