Making scrollable sections snap
permalinkI 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 permalink
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>
Into:
<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.
<div
class="w-full h-screen md:w-5/12 ml-auto overflow-y-auto snap-mandatory snap-y"
></div>
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.
<div
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>
</div>
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 permalink
Surprisingly enough, scroll snap has excellent support and can be safely used!
Thank you for reading, and let's connect! permalink
Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter