CSS-Only Carousel

Avatar of Chris Coyier
Chris Coyier on

DigitalOcean provides cloud products for every stage of your journey. Get started with $200 in free credit!

It’s kind of amazing how far HTML and CSS will take you when building a carousel/slideshow.

  1. Setting some boxes in a horizontal row with CSS Flexbox is easy.
  2. Showing only one box at a time with overflow and making it swipable with overscroll-behavior is easy.
  3. You can make the “slides” line up nicely with scroll-snap-type.
  4. A couple of #jump-links is all you need to make navigation for it, which you can make all nice and smooth with scroll-behavior.

Christian Schaefer has taken it a little further with next and previous buttons, plus an auto-play feature that stops playing once interaction starts.

About that auto-play thing — it’s a bonafide CSS trick:

  1. First I slowly offset the scroll snap points to the right, making the scroll area follow along due to being snapped to them.
  2. After having scrolled the width of a whole slide, I deactivate the snapping. The scroll area is now untied from the scroll snap points.
  3. Now I let the scroll snap points jump back to their initial positions without them “snap-dragging” the scroll area back with them
  4. Then I re-engage the snapping which now lets the scroll area snap to a different snap point 🤯

Cool.

JavaScript-powered slideshows (e.g. with Flickty) can be real nice, too. There is just something neat about getting it done with so little code.

And speaking of how far we can get with HTML and CSS, here are a few related takes on image carousels and galleries.