CSS Scroll Snap
CSS Scroll Snap allows you to lock the viewport to certain elements or locations after a user has finished scrolling. It creates a "snapping" effect, useful for carousels, full-page slides, and paginated interfaces.
1. The Container: scroll-snap-type
This property is applied to the scroll container (the parent element with overflow: scroll or auto).
Syntax: scroll-snap-type: [x | y | block | inline | both] [mandatory | proximity];
- Axis:
x: Snap horizontally.y: Snap vertically.
- Strictness:
mandatory: The browser must snap to a snap point when scrolling stops.proximity: The browser may snap if the user scrolls close enough to a snap point, but otherwise leaves it where it stopped.
.container {
overflow-x: scroll;
scroll-snap-type: x mandatory;
}
2. The Children: scroll-snap-align
This property is applied to the child elements (the items you want to snap to).
Syntax: scroll-snap-align: [none | start | end | center];
start: The start of the element aligns with the start of the scroll container.center: The center of the element aligns with the center of the scroll container.end: The end of the element aligns with the end of the scroll container.
.item {
scroll-snap-align: center;
}
3. scroll-snap-stop
This property controls whether the scroll container is allowed to "pass over" possible snap positions.
normal(default): The scroll container may pass over snap positions.always: The scroll container must snap to the first snap position it encounters. This prevents skipping items when scrolling fast.
.item {
scroll-snap-stop: always;
}
4. Padding and Margin
Sometimes headers or other fixed elements obscure the snap area.
scroll-padding: Applied to the container. Defines an offset for the snap area (e.g., to account for a sticky header).scroll-margin: Applied to the child. Defines an offset for the snap alignment on the item itself.
.container {
scroll-padding-top: 50px; /* Snap points are offset by 50px from top */
}
.item {
scroll-margin: 10px; /* Adds breathing room around the snap alignment */
}