A Quick Guide to Scroll Snap
Scroll snap is a handy viewport navigation effect that locks focus on a page element. Elements with the scroll effect applied "snap" into view.
Scroll snap works along both the y and x axes of the viewport. Often, you will see it applied to a series of cards, or used to bring focus onto specific sections of a page.
To get up and running with Scroll Snap we will need two properties:
Let's say we have a stack of slides we want to snap into place along the y-axis of the viewport.
First, we add the
scroll-snap-type property to the container element.
scroll-snap-type: y mandatory;
With this property we have a required first value
y, followed by an optional second value
y we are saying the container element can only snap along its y-axis.
mandatory ensures that whenever the scroll action completes, the browser will snap to the nearest element along the axis.
Next, we need to add
scroll-snap-align to the elements we want to snap.
Here we are saying two things:
- Snap all the child elements with the
- Snap to the
startof each slide element.
Let's see this in action:
Something to note here: We could have snapped the slides to their
end. But, with these full viewport cards, it's hard to see the difference.
Let's make it easier to see with a new example which snaps cards to their
Open up the demo yourself, substitute
center into the
snap-scroll-align property, and see how that affects the cards.
Mandatory vs. Proximity
scroll-snap-type property can take either
proximity as its second value. So far we've only touched on
mandatory. Think of it as the stricter of the two. No matter what the snap aligns to, you will see that visually dramatic snap effect.
proximity on the other hand is a "softer" snap; one that won't take effect until the scroll action is much closer to the
Let's take a look at the difference. And be sure to scroll slowly to make sure you're seeing the effect.
Lastly, let's take a quick look at what a scroll along the x-axis looks like. First let's apply our properties.
scroll-snap-type: x mandatory
Pretty much the same behavior as in our first example, only occuring along the screen's horizontal (x) axis.
At it's most basic two property setting, scroll-snap is pretty easy to set up, eh?
But it can be more involved (and you can get much more specific with your settings). I encourage you to take look at all the scroll-snap properties and consider how they could useful to you in your next project.
Thanks for reading, and happy coding!