Scroll snapping can be achieved using CSS:
- Enable scrolling on the parent element with
overflow: auto
. - Set the
scroll-snap-type
property on the parent element. - Set the
scroll-snap-align
property on the child element to snap to it.
Scroll Snapping Example
Here's an example of how to enable scroll-snapping on the x-axis using CSS:
.parent {
/* 1️⃣ enable scrolling */
overflow: auto;
/* 2️⃣ enable scroll-snapping on horizontal axis */
scroll-snap-type: x mandatory;
}
.child {
/* 3️⃣ snap to the start of the element*/
scroll-snap-align: start;
}
Here's what it looks like:
Scroll Snap Type
The scroll-snap-type
property accepts two values - axis and strictness. The axis can be:
x
- horizontal;y
- vertical;both
- both, but it may snap to different elements.
The strictness (second value) can be:
mandatory
- always snaps to the element or resets the scroll attempt if not close enough to the alignment point.proximity
- snaps only when close to the alignment point, in other cases the scroll position is left unchanged.
Scroll Snap Align
The scroll-snap-align
property accepts a single value - alignment point:
center
- the center of the element;start
- the start of the element based on the scroll-snap axis;end
- the end of the element.
Conclusion
Basic scroll snapping could be implemented without any JavaScript using the scroll-snap-type
and scroll-snap-align
CSS properties.
If you'd like to see the complete example, you can find it on my GitHub: