Skip to content
GreenSnippets

CSS-only scroll-snap carousel

A horizontally scrolling gallery that snaps to each card, with no JavaScript.

CSS
.carousel {
  display: grid;
  grid-auto-flow: column;
  grid-auto-columns: min(80%, 22rem);
  gap: 1rem;
  overflow-x: auto;
  scroll-snap-type: x mandatory;
  overscroll-behavior-x: contain;
  padding-bottom: 0.5rem;
}

.carousel > * {
  scroll-snap-align: start;
}

Example / expected output

Output
<!-- <div class="carousel" tabindex="0"> <article>…</article> <article>…</article> </div> -->

How it works

scroll-snap-type on the container and scroll-snap-align on children make swipes and wheel scrolling land neatly on items. overscroll-behavior-x: contain stops the page from navigating back when the carousel hits its end. Make the container focusable with tabindex="0" so keyboard users can scroll it with the arrow keys.

This snippet has been reviewed but was not executed by an automated test. Test it in your own environment before relying on it.