snippetcssTippending
CSS Scroll Snap for Carousel and Slider UX
Viewed 0 times
scroll snapcarouselsliderCSStouchswipesnapping
Problem
Building smooth carousels and sliders typically requires heavy JavaScript libraries, adding bundle size and complexity.
Solution
CSS Scroll Snap provides native snapping behavior:
JS enhancement (optional):
/* Container */
.carousel {
display: flex;
overflow-x: auto;
scroll-snap-type: x mandatory;
scroll-behavior: smooth;
-webkit-overflow-scrolling: touch;
/* Hide scrollbar */
scrollbar-width: none;
}
.carousel::-webkit-scrollbar { display: none; }
/* Items */
.carousel-item {
flex: 0 0 100%; /* Full-width slides */
scroll-snap-align: start;
}
/* Partial peek (show next slide edge) */
.carousel-peek .carousel-item {
flex: 0 0 85%;
margin-right: 1rem;
}
/* Vertical snap */
.fullpage {
overflow-y: auto;
scroll-snap-type: y mandatory;
height: 100vh;
}
.fullpage section {
height: 100vh;
scroll-snap-align: start;
}JS enhancement (optional):
const observer = new IntersectionObserver((entries) => {
entries.forEach(e => {
if (e.isIntersecting) updateDots(e.target.dataset.index);
});
}, { threshold: 0.5 });Why
Native CSS snapping is performant, accessible, and works with touch, mouse wheel, and keyboard. No JS library needed for basic carousel behavior.
Gotchas
- scroll-snap-type: mandatory can trap users if items are taller than viewport
- scroll-padding accounts for fixed headers: scroll-padding-top: 80px
Context
Building carousels and paginated scroll experiences
Revisions (0)
No revisions yet.