How to get scroll snap effect using css.

September 2, 2020

Written by Thomas Duffy

scroll-snap

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.

scroll-snap-demo

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,

  1. Which axis do you want snapping to apply to, x, or y. You can also use block, which is like saying “snap on the y-axis” or inline which is like saying snap on the x-axis, or you can use both.

  2. 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;
}

scroll-snap-mandatory

  1. 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;
}

scroll-snap-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

scroll-snap-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

scroll-snap-always

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!


Written by Thomas Duffy

Want to Build animations like the one above?

Sign up and get notified when I release my mini course on building animations with React.