CSS

Implement Scroll-Snapping Using Only CSS

Learn to implement scroll-snapping without any JavaScript using only CSS.

· 2 min read
Implement Scroll-Snapping Using Only CSS

Scroll snapping can be achieved using CSS:

  1. Enable scrolling on the parent element with overflow: auto.
  2. Set the scroll-snap-type property on the parent element.
  3. Set the scroll-snap-align property on the child element to snap to it.

Scroll Snapping Example

Here's an example of how to enable scroll-snapping on the x-axis using CSS:

.parent {
  /* 1️⃣ enable scrolling */
  overflow: auto;
    
  /* 2️⃣ enable scroll-snapping on horizontal axis */
  scroll-snap-type: x mandatory; 
}

.child {
  /* 3️⃣ snap to the start of the element*/
  scroll-snap-align: start;
}

Here's what it looks like:

CSS-only scroll snap example.

Scroll Snap Type

The scroll-snap-type property accepts two values - axis and strictness. The axis can be:

  1. x - horizontal;
  2. y - vertical;
  3. both - both, but it may snap to different elements.

The strictness (second value) can be:

  1. mandatory - always snaps to the element or resets the scroll attempt if not close enough to the alignment point.
  2. proximity - snaps only when close to the alignment point, in other cases the scroll position is left unchanged.

Scroll Snap Align

The scroll-snap-align property accepts a single value - alignment point:

  1. center - the center of the element;
  2. start - the start of the element based on the scroll-snap axis;
  3. end - the end of the element.

Conclusion

Basic scroll snapping could be implemented without any JavaScript using the scroll-snap-type and scroll-snap-align CSS properties.

If you'd like to see the complete example, you can find it on my GitHub:

twitter-code/src/scroll-snap at main · vincaslt/twitter-code
Code examples from my Twitter @VincasStonys. Contribute to vincaslt/twitter-code development by creating an account on GitHub.