Aligning Scrolled Elements with scroll-snap-align in CSS

As shown in the example above, Scroll Snap also requires the scroLL-snap-aLign property. This property gets applied to the children of a Scroll Snap container. It accepts up to two values: the first indicates the snapping alignment along the block axis, while the second indicates the snapping alignment along the inline axis:

.scroll-container p {

scroll-snap-align: none center;

}

The CSS above says to the browser: “Don’t snap vertical scrolling, and snap horizontal scrolling to the center position of each child element.” The image below shows the effect. Our child element is centered within the Scroll Snap container.

The following properties are valid scroLL-snap-aLign values, and the property accepts up to two snap alignment positions:

  • none : initial value; don’t snap scroll in either direction
  • start : snap to the start of the element’s box
  • end : snap to the end of the element’s box
  • center : snap to the middle of the element’s box

When scroLL-snap-aLign has a single position, that value is used for both axes. In other words, scroLL-snap-aLign: center is the same as scroLL-snap-aLign: center center . Whether start and end align to the right or left edge depends on the writing mode of the document.

Let’s change the value of scroLL-snap-aLign from none center to none start . Now, instead of our child element being centered within the snapport, its starting edge is aligned to the starting edge of the container, as pictured below.

Using scroLL-snap-aLign: none end or scroLL-snap-aLign: end , on the other hand, aligns the ending edge of our child element to the ending edge of the container.

Source: Brown Tiffany B (2021), CSS , SitePoint; 3rd edition.

Leave a Reply

Your email address will not be published. Required fields are marked *