Learn its use cases and available options to control the top margin of scroll snap areas.
Introduction
The scroll-margin-top
property in CSS defines the top margin of the scroll snap area, helping to snap an element to a specific position in the scroll container. This feature has been available since July 2019 and works well across many devices and browsers.
Specification
The scroll-margin-top
property is part of the CSS Scroll Snap Module Level 1 specification. This module provides precise control over scrolling behavior, allowing elements to snap into place within a scroll container.
Description
The scroll-margin-top
property defines the top margin of the scroll snap area. This margin determines the spacing between the top edge of an element and the top of the scroll container when the element snaps into place. It creates extra space above the element, enhancing the visual and functional aspects of scrolling.
The value of scroll-margin-top
can be set using length units like pixels (px), ems (em), or other CSS length units. The property also supports global CSS values like inherit
, initial
, revert
, revert-layer
, and unset
.
Syntax
Values
Length Values
px
(pixels):em
(relative to the font-size of the element):rem
(relative to the font-size of the root element):vh
(viewport height):
Global Values
inherit
:initial
:revert
:revert-layer
:unset
:
Formal Definition
- Initial Value:
0
- Applies To: All elements
- Inherited: No
- Computed Value: Same as specified value
- Animation Type: By computed value type
Browser Compatibility
- Google Chrome: 69+
- Microsoft Edge: 79+
- Firefox: 68+
- Opera: 56+
- Safari: 14.1+
Example
HTML
Explanation
- .container: The scrollable container with a fixed width and height. It uses
scroll-snap-type: y mandatory
to enable mandatory snapping in the vertical direction. - .section: Each section is a child of the container and has a fixed height. The
scroll-snap-align: start
property ensures that the top of each section aligns with the top of the container when snapping. - .section1, .section2, .section3, .section4: Each section has a different background color and a unique
scroll-margin-top
value, allowing you to see how the property affects the scrolling behavior.
Additional Resources
- CSS Scroll Snap Documentation: WebsiteUrl
- CSS Scroll Snap Examples: WebsiteUrl
- Related CSS Properties:
scroll-snap-align
scroll-snap-type
scroll-padding-top
- Web Development Resources:
- MDN Web Docs: WebsiteUrl
- Google Web Fundamentals: WebsiteUrl
- CSS Tricks: WebsiteUrl
- Learning and Community:
- Stack Overflow: WebsiteUrl
- GitHub: WebsiteUrl
- Dev.to: WebsiteUrl
We'll be right here with you every step of the way.
We'll be here, prepared to commence this promising collaboration.
Whether you're curious about features, warranties, or shopping policies, we provide comprehensive answers to assist you.