Scroll snap

  • #html
  • #css
Posted on 24 November 2019
Scroll snap is a CSS property letting you set the behaviour of the overflowing scrolling items.

Why use scroll snap functionality?

Scroll snap feature allows for displaying a scrolling piece of content in the optimal position. It's a common approach, especially on mobile devices and tablets, to display only a portion of the content and let the rest of it overflow out of the view. It's up to the user then to scroll the hidden items into the view.

The default overflowing content with no scroll snapping.
Image by Joanna Kosinska Image by Joanna Kosinska Image by Joanna Kosinska Image by Joanna Kosinska Image by Joanna Kosinska
HTML structure:
<div class="scroll-x">
    <div class="scroll-x__wrapper">
        <img src="/assets/images/blog-scroll-snap.jpg" alt="Image by Joanna Kosinska">
        <img src="/assets/images/blog-scroll-snap.jpg" alt="Image by Joanna Kosinska">
        <img src="/assets/images/blog-scroll-snap.jpg" alt="Image by Joanna Kosinska">
        <img src="/assets/images/blog-scroll-snap.jpg" alt="Image by Joanna Kosinska">
        <img src="/assets/images/blog-scroll-snap.jpg" alt="Image by Joanna Kosinska">
    </div>
</div>

But we can take away the fiddly work from the user by adding the new behaviour rules.

Horisontal scroll snap CSS:
    .scroll-snap-x{
        overflow-x: auto;
        scroll-snap-type:x mandatory; /* mandatory|proximity */
        max-height: 320px;
        max-width: 320px;
    }

    .scroll-snap-x__wrapper{
        display: flex;
    }

    .scroll-snap-x img{
        scroll-snap-align: center; /* center|start|end */
    }
Now that's much better:
Image by Joanna Kosinska Image by Joanna Kosinska Image by Joanna Kosinska Image by Joanna Kosinska Image by Joanna Kosinska

How about vertical scroll snap?

Yes, scroll snap also supports Y axis. Just flip the x's for y's and you should be good to go.
Image by Joanna Kosinska Image by Joanna Kosinska Image by Joanna Kosinska Image by Joanna Kosinska Image by Joanna Kosinska

Scroll snap browser support.

The global support for this feature reaches 87% according to Can I Use and can be accessed even by the IE 10 users if prefixed. That's pretty decent considering it's an enhancement to the scrolling functionality, so when the support is missing, users can still navigate through the content without noticing a difference.

Photo by Joanna Kosinska