Cover photo credit: Teemu Paananen
One of the things I’ve been wanting to do for a while is to play with CSS scroll-snap. There are a lot of practical applications for using scroll-snap. Image carousel, sectioning out a blog, and our focus for today, slideshows!
Scroll-snap is designed to create a set of scroll positions within a scroll container. This really means that within a scrollable container we can control how the internal elements land while the user is scrolling.
An example is usually the quickest way to demonstrate this behavior.
There are 3 important CSS rules to notice:
- overflow-y: scroll;
- scroll-snap-type: y mandatory;
- scroll-snap-align: start;
ul is given a fixed height with an
scroll. This basically sets up a scrollable container for all of the
li tags within. Then we tell the scrollable container to set
y mandatory, dictating that we want the children to snap as the container is scrolled in the
y direction. The last step is to tell the child elements how to snap.
scroll-snap-align is the rule that tells the
li tags to align the
start of their elements with the top of container.
There are a few different snapping behaviors we can achieve. The first we already demonstrated:
mandatory forces the child elements to snap no matter where the user is in their scrolling process. The other option here is
proximity which allows scrolling to happen normally, and only if the user stops scrolling near the snap point will it snap to the top.
Here’s a side by side to play around with:
Controlling which part of the child items aligns with the container is an important part of using scroll-snap.
scroll-snap-align has only 4 values, and they are reasonably self explanatory:
The basic idea is that you are choosing which part of the child element is going to be aligned to the container.