Home / Snippets / Layout & Grid /
Scroll snap image gallery
A horizontal gallery that snaps cleanly to each item — no JavaScript needed.
Quick implementation
.gallery {
display: flex;
gap: 1rem;
overflow-x: auto;
scroll-snap-type: x mandatory;
scroll-padding: 1rem;
-webkit-overflow-scrolling: touch;
}
.gallery-item {
flex: 0 0 min(20rem, 80vw);
scroll-snap-align: start;
aspect-ratio: 4 / 3;
border-radius: 0.5rem;
object-fit: cover;
}
Prompt this to your LLM
Paste this into ChatGPT, Claude, or any LLM to build a snap gallery.
Create a horizontal scroll-snap image gallery using CSS. The container
uses display: flex, overflow-x: auto, and scroll-snap-type: x mandatory
with scroll-padding: 1rem. Each item uses flex: 0 0 min(20rem, 80vw),
scroll-snap-align: start, and aspect-ratio: 4/3. Images should use
object-fit: cover with border-radius. No JavaScript. Add smooth
touch scrolling with -webkit-overflow-scrolling: touch.
Why this matters
Carousels and image galleries are everywhere — product pages, portfolios, stories. Traditionally they required heavy JavaScript libraries. CSS scroll snap gives you the same snapping behavior natively, with smooth momentum scrolling on touch devices and no bundle-size cost. Users get a familiar, polished interaction for free.
The logic
scroll-snap-type: x mandatory tells the browser to always snap to a snap point after scrolling stops. Each item declares scroll-snap-align: start to snap its left edge to the container's left edge. scroll-padding offsets the snap point inward so items do not press flush against the container edge. flex: 0 0 min(20rem, 80vw) sizes items to 20rem or 80% of the viewport (whichever is smaller), ensuring they work on mobile too. mandatory vs proximity — mandatory always snaps, proximity only snaps when close to a snap point.
Accessibility & performance
Add role="list" to the gallery container and role="listitem" to each item if not using semantic list elements. Include aria-label on the container (e.g. "Image gallery"). Keyboard users can scroll with arrow keys. For images, always provide descriptive alt text. CSS scroll snap is hardware-accelerated on all modern browsers, so performance matches native scrolling. Use loading="lazy" on off-screen images to reduce initial load.