Making scrollable sections snap


How to make scrollable sections snap to the top with CSS

21 Mar, 2021 ยท 2 min read

I created this cool section scroll in Tailwind. However, I would almost expect the sections to snap while I'm close to them as a user.

So today, I'll show you how to make the sections snap!

You can try it out on the following Codepen.

See the Pen Making scrollable sections snap by Chris Bongers (@rebelchris) on CodePen.

Making the sections snap with CSS

Let's use the code as we had previously. There are, however, a couple of things we will need to change.

First of all, our current wrapping container for the sections has an infinite height, meaning it will become as big as the children are.

For the scroll snap to work, it must be as big as the screen.

Change the following:

<div class="w-full md:w-5/12 ml-auto"></div>


<div class="w-full h-screen md:w-5/12 ml-auto overflow-y-auto"></div>

You can see we add the h-screen class, which will make this section exactly our viewport height. We also add overflow on the y-axis to auto.

That's already half the work. Now let's add the scroll-snap magic.

Old: Unfortunately, Tailwind does not come with these classes. For the ease of this tutorial, I'll add two custom classes.

Yeah, Tailwind V3 now comes with scroll snap classes, so let's add the scroll snap behavior we want on the parent element.

  class="w-full h-screen md:w-5/12 ml-auto overflow-y-auto snap-mandatory snap-y"

We used snap-mandatory to define how the snapping should behave and define the axis on which it acts, which is snap-y for our demo.

Then we need to add a class to each section to define how it snaps to the parent. In our case, we want it to snap to the top.

  class="bg-red-200 h-screen flex justify-center items-center flex-col p-10 snap-start"
  <h2 class="text-4xl mb-5">Meet Benny</h2>
  <p class="mb-5">I was born 20 May 2020</p>

This tells the scroll-snap were to snap to. In most cases, you'd like the start. It will snap the element to the top of the scroll-snap container.

However, you can also choose between: end, center, or none.

And that's as simple as it gets.

Browser support

Surprisingly enough, scroll snap has excellent support and can be safely used!

CSS Scroll-snap support

Thank you for reading, and let's connect!

Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter

Spread the knowledge with fellow developers on Twitter
Tweet this tip
Powered by Webmentions - Learn more

Read next ๐Ÿ“–

CSS Logos: Vue logo

22 Jun, 2022 ยท 3 min read

CSS Logos: Vue logo

CSS Logos: Strava logo

21 Jun, 2022 ยท 5 min read

CSS Logos: Strava logo

Join 1513 devs and subscribe to my newsletter