CSS scroll snap
The CSS scroll snap API offers this for the web. In essence, you need two things. A container that needs to be scrolled in and items to snap to. Firstly, you add the
scroll-snap-type property to the container:
scroll-snap-type: y mandatory;
y is the direction you want to snap to. In this example, we want to snap while the user is scrolling vertically.
mandatory is one of the values you can use to always snap:
The visual viewport of this scroll container will rest on a snap point if it isn't currently scrolled. That means it snaps on that point when the scroll action finished, if possible. If content is added, moved, deleted or resized the scroll offset will be adjusted to maintain the resting on that snap point.
Next, we can tell the items where we would like to align the scroll snapping to. You can do this by using the
scroll-snap-align property on the item:
And that's it! This is all we need to implement scroll snapping with CSS only. Have a look at the interactive demo over at Codepen or below. Thanks for reading!