NoLoJS logo

CSS Carousel - Snappy Swiper

With one line of additional CSS, the slides “snap” into place as the user swipes (in the center, in this case). Note that even when dragging the scrollbar, the “snap to the center” still happens after releasing the scrollbar, all CSS, no JS required.

Demo

HTML

<!-- No special HTML -->
<ul class="css-carousel">
  <li>Slide 1</li>
  <li>Slide 2</li>
  <li>Slide 3</li>
  <li>Slide 4</li>
  <li>Slide 5</li>
  <li>Slide 6</li>
  <li>Slide 7</li>
  <li>Slide 8</li>
  <li>Slide 9</li>
  <li>Slide 10</li>
</ul>

CSS

/* Basic carousel CSS */
.css-carousel {
  /* Resets for carousel appearance */
  list-style: none;
  padding: 0;
  /* The only CSS necessary for a simple swiper Carousel */
  display: flex;
  overflow-inline: auto;
  /* Prevents accidental page Back/Forward */
  overscroll-behavior-inline: contain;
  /* Confines the scrolling direction */
  scroll-snap-type: inline mandatory;
  /* Be nice to others */
  @media (prefers-reduced-motion: no-preference) { 
    /* Makes the sliding a little smoother */
    scroll-behavior: smooth;
  }
  /* Add snap-to position */
  li {
    /* Make things look a little nicer */
    min-width: 200px;
    aspect-ratio: 1 / 1;
    border: 1px solid;
    place-content: center;
    text-align: center;
    /* Optionally force swipes to center the new slide; can also use: `start` or `end` */
    scroll-snap-align: center;
    /* Optionally force swipes to stop for each slide; can also use: `normal` */
    scroll-snap-stop: always;
  }
}

JS

No JS required.

Baseline

[`scroll-behavior`](https://webstatus.dev/features/scroll-behavior) [`scroll-snap`](https://webstatus.dev/features/scroll-snap)

CodePen

See the Pen on CodePen.