Today I learned November 1, 2019 2 min read — css

CSS Snap Scrolling

What is it?

Recently I was building yet another carousel component for one of our landing pages at work, when I came across a new CSS feature I haven't heard about before: CSS snap scrolling.

The idea is simple. Instead of normal scrolling behaviour, we can define a snappy scrolling behaviour. The browser does the rest for us. No need for complex JS calculations and animations 🎉

Example and attributes

The most important two basic attributes to enable scroll snapping are:

  • scroll-snap-type: applied to the container
  • scroll-snap-align: applied to the children, to be scrolled within the container
.container {
  scroll-snap-type: x mandatory;
}

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

Be aware that there is a legacy version of the spec that some older browsers use, make sure to check the CSS tricks article or the specific browser docs for more details.

Other attributes you might need are:

  • scroll-padding: padding distance, e.g. if you have fixed elements on top of the scroll container you want/need to account for
  • scroll-snap-stop: controlling when the snap behaviour should kick in

This TIL is pretty brief, since I found this after I already implemented the slider in React and JS, so I don't have any actual in depth experience regarding implementation. But I'll definitely use it the next time I have to write a slider component 😊

The most important of all questions: what does browser support look like?

Actually, not too bad. All major browsers are supported, including IE back to version 1 (using the browser specific -ms-* prefix, at least partially).

There is a polyfill available if you really need it, that covers most of the basic functionality.