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
scroll-snap-typegoes on the scroller;scroll-snap-alignon each item.scroll-paddingkeeps a sticky header from covering the snapped item.overscroll-behavior: containstops the page scrolling once this ends.
Keywords and builtins used here
carouseldisplayflexgapminrem
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.
Step 7 of 7 in Positioning, step 23 of 24 in Flexbox & grid.