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;
}
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;
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)