HiveBrain v1.2.0
Get Started
← Back to all entries
snippetcssTip

Horizontal or vertical scroll snap in CSS

Submitted by: @import:30-seconds-of-code··
0
Viewed 0 times
verticalscrollcsssnaphorizontal

Problem

Scroll snapping in CSS has been around for a while and it's a great way to create modern interactive experiences. It consists of a handful of properties that allow you to create a scrollable container that will snap on elements when scrolling, either horizontally or vertically.
To create a scrollable container that snaps on elements when scrolling, you can use the scroll-snap-type property to control the snap axis. This property can be set to x for horizontal scrolling or y for vertical scrolling. You can also set it to both to enable both horizontal and vertical scrolling.
> [!TIP]
>
> If you're working with the new Logical Properties you can use block for vertical and inline for horizontal. In this article, however, we'll focus on the more traditional x and y values.

Solution

/* Horizontal scroll snap */
.scroll-snap {
  scroll-snap-type: x mandatory;
}

/* Vertical scroll snap */
.scroll-snap {
  scroll-snap-type: y mandatory;
}


> [!TIP]
>
> If you're working with the new Logical Properties you can use block for vertical and inline for horizontal. In this article, however, we'll focus on the more traditional x and y values.
Apart from the snap axis, you can also specify the snap strictness with scroll-snap-type. The mandatory value will snap the container to the nearest snap point, while proximity will snap the container to the nearest snap point if it's close enough (default).
You can also control the alignment of the snap points using the scroll-snap-align property. This property can be set to start, end, center, or none.
To prevent the default browser behavior when reaching the end of the scrollable container, you can use the overscroll-behavior property. This property can be set to auto, contain, or none.

Code Snippets

/* Horizontal scroll snap */
.scroll-snap {
  scroll-snap-type: x mandatory;
}

/* Vertical scroll snap */
.scroll-snap {
  scroll-snap-type: y mandatory;
}
/* Snap to the start of the element */
.scroll-snap > .element {
  scroll-snap-align: start;
}

/* Snap to the center of the element */
.scroll-snap > .element {
  scroll-snap-align: center;
}

/* Snap to the end of the element */
.scroll-snap > .element {
  scroll-snap-align: end;
}
/* Horizontal scroll snap */
.scroll-snap {
  scroll-snap-type: x mandatory;
  overscroll-behavior-x: contain;
}

/* Vertical scroll snap */
.scroll-snap {
  scroll-snap-type: y mandatory;
  overscroll-behavior-y: contain;
}

Context

From 30-seconds-of-code: scroll-snap

Revisions (0)

No revisions yet.