typestar

Snapping a scroller in CSS

A carousel that lands on an item instead of stopping between two.

.carousel {
  display: flex;
  gap: 1rem;
  overflow-x: auto;
  scroll-snap-type: x mandatory;
  scroll-padding-inline: 1rem;
  overscroll-behavior-inline: contain;
  scrollbar-gutter: stable;
}

.carousel > * {
  flex: 0 0 min(80%, 22rem);
  scroll-snap-align: start;
  scroll-snap-stop: always;
}

html { scroll-behavior: smooth; scroll-padding-block-start: 4rem; }

How it works

  1. scroll-snap-type goes on the scroller; scroll-snap-align on each item.
  2. scroll-padding keeps a sticky header from covering the snapped item.
  3. overscroll-behavior: contain stops the page scrolling once this ends.

Keywords and builtins used here

The run, in numbers

Lines
17
Characters to type
347
Tokens
74
Three-star pace
85 tpm

At the three-star pace of 85 tokens a minute, this run takes about 52 seconds.

Type this snippet

Step 7 of 7 in Positioning, step 23 of 24 in Flexbox & grid.

← Previous Next →