Sustainable.devBETA Menu

Posted to Resource on January 21, 2021


Create a snap scroll interaction – without JavaScript

Another simple method that can reduce the JavaScript you use by replacing it with a pure CSS solution.

 
Introduced way back in 2016, scroll-snap has been about for a while.

It is well supported across most browsers now, even legacy browser IE11 has a certain implementation using an older spec. Though, I won’t cover that here.

How to use scroll-snap

The basics can be written in a couple of lines of CSS. The example below will add a snap scroll interaction within the parent container so that when scrolled in the Y direction, child elements ‘snap’ to the top.

.parent {
 height: 300px;
 overflow-y: scroll;
 scroll-snap-type: y mandatory;
}

.child {
 scroll-snap-align: start;
}

Here is an example on CodePen. As you’ll see, it can feel like a nice enhancement but can have the potential to cause issues depending on the content within the child sections and the user’s preferences on motion. I’d suggest teaming this with the prefers-reduced-motion media query for a better progressive enhancement to a site.

Further reading

Scroll-snap has been written about quite a lot, here are a few good places to learn more about the options you can use.

MDN docs – CSS Scroll Snap
CSS Tricks – Practical CSS Scroll Snapping