DEV Community

WDSEGA
WDSEGA

Posted on • Originally published at wdsega.github.io

Component Deep Dive #13: Responsive Image Carousel — The CSS Grid Trick You Need

The image carousel is the web's oldest interactive component — and its most bug-ridden. Here's how to build one that actually works across all screen sizes.

The Core Trick

.carousel-slide img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
Enter fullscreen mode Exit fullscreen mode

object-fit: cover is the soul of responsive carousels. Unlike old-school background-image hacks, <img> with object-fit is SEO-friendly and screen-reader-compatible.

The Seamless Loop Formula

this.current = ((index % len) + len) % len;
Enter fullscreen mode Exit fullscreen mode

JavaScript's % is remainder, not modulo — -1 % 5 returns -1. The double-modulo ensures positive indices going both forward and backward.

Touch vs Click

Track touchstart position. Only treat a gesture as a swipe if horizontal movement exceeds 30px. This prevents accidental navigation during scrolling.

Full code with autoplay, pause-on-hover, and indicator dots available below.


This component is part of Web Component Dictionary v2.0 — 83 components, 8 categories, bilingual docs, live previews. One-time purchase ¥9.99.
Live demo: wdsega.github.io/web-components

Top comments (0)