CSS Scroll Snap

How to use the CSS Scroll Snap property for page-level vertical scrolling

Guides ->

2 minute read

The CSS Scroll Snap property allows you to adjust the scrolling behaviour of the browser to better align with your content.

The desired effect can be seen here: scroll-snap-demo.vercel.app

The most straightforward way to achieve this is to have child elements that make up the page content, along with a parent element that wraps the content.

<div class="scroll-parent">
  <div class="scroll-child">
    <p>Child 1 Content</p>
  </div>
  <div class="scroll-child">
    <p>Child 2 Content</p>
  </div>
  <div class="scroll-child">
    <p>Child 3 Content</p>
  </div>
</div>

In the above example, .scroll-parent and .scroll-child are used. Next, you need to apply the following two sets of styles to the container and the child elements, respectively:

/* the container element */
.scroll-parent {
  /* make the container overflow vertically */
  height: 100vh;
  overflow-y: auto;

  /* define scroll snap behaviour */
  scroll-snap-type: y mandatory;
}

/* the child element */
.scroll-child {
  /* adjust based on desired behaviour */
  scroll-snap-align: start; /* start or center or end */

  /* add for a slideshow-like feel */
  height: 100vh;
}

You can view the source code on GitHub. Feel free to copy as much as you want.

In terms of edge cases, please bear in mind that you should exercise caution when modifying the scroll behaviour of your page, as it can lead to some unintended side effects, such as the user not being able to scroll to certain parts of your page, a behaviour which CSS Tricks explains well.

Last Updated: 1649470068000

Edit on GitHub ->