Scroll Snap

Scroll horizontally to see how each slide snaps neatly into place. This is powered by scroll-snap-type and scroll-snap-align.

Code Example

<div class="carousel">
  <div class="slide">Slide 1</div>
  <div class="slide">Slide 2</div>
  <div class="slide">Slide 3</div>
</div>

.carousel {
  display: flex;
  overflow-x: auto;
  scroll-snap-type: x mandatory;
  scroll-behavior: smooth;
  gap: 1rem;
}

.slide {
  flex: 0 0 100%;
  scroll-snap-align: start;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 2rem;
  font-weight: bold;
  color: white;
  height: 300px;
  border-radius: 8px;
}

    .slide:nth-child(1) { background: #e63946; }
    .slide:nth-child(2) { background: #457b9d; }
    .slide:nth-child(3) { background: #2a9d8f; }

Explaining the Code

.carousel { display: flex; }
Uses Flexbox to lay out the slides horizontally in a row.
overflow-x: auto;
Allows horizontal scrolling when the slides extend beyond the viewport.
scroll-snap-type: x mandatory;
Enables snapping along the horizontal axis. mandatory means the scroll always snaps to a slide.
scroll-behavior: smooth;
Makes the snapping animation smooth instead of abrupt.
gap: 1rem;
Adds spacing between each slide for visual clarity.
.slide { flex: 0 0 100%; }
Each slide takes up the full width of the viewport, so you see one at a time.
scroll-snap-align: start;
Tells the browser to align the start of each slide with the viewport when snapping.
display: flex; align-items: center; justify-content: center;
Centers the text inside each slide both vertically and horizontally.
font-size: 2rem; font-weight: bold; color: white;
Styles the slide text to be large, bold, and readable against the colored background.
height: 300px; border-radius: 8px;
Gives each slide a fixed height and rounded corners for a modern look.
.slide:nth-child(1/2/3)
Applies different background colors to each slide for visual distinction.

Deeper Breakdown of Key CSS

.slide { flex: 0 0 100%; }
flex: 0 0 100%; is shorthand for three values:
  • flex-grow: 0 → The slide will not grow larger than its set width.
  • flex-shrink: 0 → The slide will not shrink smaller than its set width.
  • flex-basis: 100% → Each slide takes up 100% of the container’s width.
Result: Each slide fills the entire viewport horizontally, so you only see one slide at a time.
display: flex; align-items: center; justify-content: center;
These properties turn each slide into a flex container:
  • display: flex → Activates Flexbox layout inside the slide.
  • align-items: center → Vertically centers the content within the slide.
  • justify-content: center → Horizontally centers the content within the slide.
Result: The text inside each slide is perfectly centered both vertically and horizontally.
Scroll Snap Demo