How to get scroll snap effect using css.
Written by Thomas Duffy
In this post I’m going to breakdown the CSS Scroll Snap Module. The Scroll Snap Module allows you to snap the viewport at specific elements on the page to create this type of effect.
This feature is excellent for image sliders, card rows, or any use case to create this fantastic snapping effect while scrolling. The scroll-snap-type
property works on the x
and y
axis to apply the snapping effect on horizontal and vertical scrolling.
To use scroll-snap
you give the parent scroll container the property of scroll-snap-type
: and decide the following,
-
Which axis do you want snapping to apply to,
x
, ory
. You can also useblock
, which is like saying “snap on the y-axis” orinline
which is like saying snap on the x-axis, or you can use both. -
Next, we have to decide if we want to force each element to a snap point no matter where the user is while scrolling, in which case you would use the value
mandatory
.
.parent-scroll-container {
scroll-snap-type: y mandatory;
}
- You can also set this property to
proximity
, which snaps if the user is close to the snap point.
.parent-scroll-container {
scroll-snap-type: y proximity;
}
Now we have to set our snap points! We do this by giving the child elements you want to snap to a property of scroll-snap-align
and decide where in the element you would like the snap effect to align on, start
, center
, or end
.
.parent-scroll-container {
scroll-snap-type: y proximity;
}
.child-element {
scroll-snap-align: start;
}
You can also force a snapping effect on every element by using a property called scroll-snap-stop
. To use scroll-snap-stop, you give it a value of always
, which says that no matter what velocity the user is scrolling, I want to stop and snap-on every element.
.parent-scroll-container {
scroll-snap-type: y proximity;
}
.child-element {
scroll-snap-align: start;
scroll-snap-stop: always;
}
scroll-snap-stop set to always
If you want the user to be able to scroll past a snap point when scrolling fast, you can leave this property out or set it to the default value of normal
.
scroll-snap-stop default or normal
Browser Support
Broswer Support is really good for this feature, so snap away!
Scroll snap is a feature that can add a nice seamless feel to a webpage. It’s built on top of the browser’s native scroll behavior, so there is no real risk of negatively impacting the UX by getting the scroll jitters or creating scroll jank.
If you found this post helpful, please feel free to sign up for my newsletter to be notified when I post the newest articles about web development!