For a long time, Web Developers have had to rely on JavaScript to perform a “scroll snap” animation. However, JavaScript libraries can be heavy and slow your site down. However, now we have CSS Scroll Snap which is relatively new and at the moment it isn’t supported in all browsers.

Gif of scroll snap

The Sauce

I hate long-winded articles so here’s the sauce:

<div className="portfolio-parent" style={{height: '100vh'}}>

<h2 className="here" style={{height: '100vh', backgroundColor: 'red'}}>here 1</h2>
<h2 className="here" style={{height: '100vh', backgroundColor: 'blue'}}>here 2</h2>

</div>

Here we have the JSX (for all intents and purposes, the same thing as HTML). I have a container with the class name “portfolio-parent”, and two children called “here”.

Think of the parent as the window you will be looking at, and the children will be the content. The heights do not need to be “100vh”, but it’s what I am going for on my site.


.portfolio-parent {
scroll-snap-type: y mandatory;
overflow-y: scroll;
}

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

As you can see, the CSS is very simple. First, you tell the parent element that the “scroll-snap-type” should be “y” as in, along the y-axis (up and down). The “mandatory” only makes sense if you know about the other option, “proximity” essentially allows some freedom in terms of scrolling. With “proximity”, you don’t need to always be snapped to an element. With “mandatory”, it is mandatory that you are snapped to an element when you are inside the parent.

If that made no sense, then, just use mandatory and don’t worry about what’s going on.

via GIPHY

To actually be able to scroll we use “overflow-y: scroll”, that’s simple.

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

Now, think of “scroll-snap-align” as the anchor for your scroll, if the browser is automatically scrolling, it needs a place to stop. There are several options, however for vertical scrolling, “start” is optimal, for horizontal “center” is optimal.

In Closing

This has been a quick overview of CSS Scroll-Snap. If you enjoy this article please share it on a platform of your choosing!

You can also see related posts on my blog at https://zacbanas.com/category/web-development-archives/