The CSS scroll-margin property controls the extra space around an element when it is scrolled into view using scroll snapping, anchor links, or JavaScript methods like scrollIntoView(). It acts like a βbuffer zoneβ between the element and the scroll container.
Note
β Does NOT change layoutβonly scroll positioning
β Often used with scroll-snap-align, anchors, and sticky headers
π¦ Syntax
scroll-margin syntax
scroll-margin: <length>;| Property | Purpose |
|---|---|
| scroll-margin | Shorthand for all sides |
| scroll-margin-top | Space before element when scrolled |
| scroll-margin-right | Right-side scroll offset |
| scroll-margin-bottom | Offset after scrolling |
| scroll-margin-left | Left-side scroll offset |
π Why Use scroll-margin?
- Prevent anchor links from being hidden behind sticky headers
- Improve scroll-snapping behavior
- Add spacing without changing layout
- Fine-tune scrollIntoView() positioning
β¨ 1. Basic Example
Basic scroll-margin
section {
scroll-margin-top: 50px;
}Now when the section scrolls into view (via anchor or JS), it appears with 50px space above it.
β¨ 2. Fix Sticky Header Anchor Problem
Sticky headers often overlap content when clicking anchor links like<a href="#contact">Contact</a>.
Offset anchor target
#contact {
scroll-margin-top: 80px; /* matches header height */
}Note
β¨ 3. Use with scrollIntoView()
JavaScript + scroll-margin
document.querySelector('#section3')
.scrollIntoView({ behavior: 'smooth' });scroll-margin modifies where the target stops.
β¨ 4. Scroll Snap + scroll-margin
Perfect for carousels, full-page sliders, and timelines.
Snap alignment improved with scroll-margin
.slide {
scroll-snap-align: start;
scroll-margin-left: 20px;
}β¨ 5. Shorthand Version
Shorthand scroll-margin
.card {
scroll-margin: 20px 10px;
}Same order as margin:top right bottom left
π§ͺ Real-World Use Cases
1οΈβ£ Section Navigation
Sections with breathing room
section {
scroll-margin-top: 60px; /* header height */
}2οΈβ£ Carousel or Slider
Card slider
.card {
scroll-snap-align: center;
scroll-margin: 0 15px;
}3οΈβ£ Chat or Logs View
Message scroll
.message {
scroll-margin-bottom: 40px;
}β οΈ Common Mistakes
- β Expecting it to change actual spacing (it only affects scrolling)
- β Using it on non-scrollable containers
- β Forgetting scroll-margin works only when the element becomes a scroll target
- β Confusing scroll-margin with scroll-padding
Note
β scroll-padding adjusts the container
π₯ Summary
scroll-margin gives you fine control over how elements position themselves when brought into view. It is essential for anchor navigation, scroll snapping, and sticky header layouts.