Scroll Snap Carousel Native
Build a native scroll snapping carousel using CSS scroll-snap with mandatory snapping and hidden scrollbars.
Code
.carousel {
display: flex;
overflow-x: auto;
scroll-snap-type: x mandatory;
scrollbar-width: none;
gap: 1rem;
}
.carousel::-webkit-scrollbar { display: none; }
.carousel-item {
flex: 0 0 80%;
scroll-snap-align: center;
scroll-snap-stop: always;
}
@media (min-width: 768px) {
.carousel-item { flex-basis: 40%; }
}
@media (min-width: 1024px) {
.carousel-item { flex-basis: 25%; }
}Inside the snippet
display: flex distributes the children along one axis, and the alignment properties decide how leftovers are handled.
scroll-snap aligns the scroll position to declared snap points after a gesture ends.
gap spaces grid/flex items without margins on the children.
2 media queries adjust the layout where the current arrangement stops fitting.
The rules target .carousel, .carousel-item, } @media (min-width: 1024px) — each selector names the element it restyles, in source order.
FAQ
- Which elements does this stylesheet target?
- The rules bind to `.carousel`, `.carousel-item`, `} @media (min-width: 1024px)`; when two rules tie in specificity, the one written later in the file wins.
Report a problem with this exampleOpens a pre-filled issue on GitHub.