Again: an element is a scroll container when the total width and/or height of its children (along with any margins or gaps) overflows its horizontal or vertical dimension. To make it a scroll snap container, we need to add the scroLL-snap-type property. Here’s an example. First, let’s look at our markup:
<div class=”scroll-container”> <p>A</p>
<p>B</p>
<p>C</p> <p>D</p>
<p>E</p>
<p>F</p>
<p>G</p>
<p>H</p>
<p>I</p>
</div>
This markup is simple. We have a containing <div> element, with a class name of scroLL- container . Its children are all <p> elements. We we could just as well use <div> or <img> elements as child elements. Here’s the CSS:
.scroll-container {
display: flex;
gap: 2rem;
/*
-
-
- These two properties force the element to be a scrolling
- The value of overflow should be auto or scroll
-
*/
width: 100vw;
overflow-x: auto;
/*
-
-
- Makes the element a Scroll Snap container
-
*/
scroll-snap-type: x mandatory;
}
.scroll-container p {
/*
-
-
- Makes every flex item exactly 40vw. The total width of
- the children overflows the width of the container
-
*/
flex: 0 0 40vw;
/*
-
-
- Where to snap after scrolling
-
*/
scroll-snap-align: none center;
}
The scroLL-snap-type property indicates two things: the Scroll Snap axis and its strictness. In this example, we’ve used scroLL-snap-type: x mandatory . That first value, x , means that our container will scroll horizontally; mandatory indicates that the container must snap to a position when it isn’t being scrolled.
You must specify the scroll axis for scroLL-snap-type . In addition to none (the initial value), and CSS global values, the value of scroLL-snap-type can be any of the following:
- inline : scrolls in the inline direction—horizontally for languages written and read from left to right or right to left, and vertically for vertical writing modes
- block : scrolls in the block direction—vertically for languages written and read from left to right or right to left, and horizontally for vertical writing modes
- x : scrolls horizontally
- y : scrolls vertically
- both : scrolls both horizontally and vertically
Since the scroll axis is a mandatory value, it must be listed first. The Scroll Snap strictness value, on the other hand, is optional. Its value can be one of the following:
- none : no snapping occurs
- proximity : may snap to a position after a scrolling operation completes, at the discretion of the user agent
- mandatory : must snap to a snap position when there’s no scrolling operation in progress
If you don’t indicate the strictness of a Scroll Snap, the browser uses proximity . Using mandatory , however, ensures that the browser snaps to the position you indicate.
The scroLL-snap-type property sets the scrolling behavior on the containing element. For the snap to work, we also need to indicate how child elements should be aligned within the container when a scrolling operation completes.
Source: Brown Tiffany B (2021), CSS , SitePoint; 3rd edition.