How to create an image carousel with HTML, CSS and JavaScript
Building an image slider from scratch is a great way to understand how web pages handle movement and user interaction. This guide breaks down the HTML, CSS, and JavaScript needed to build a responsive carousel that runs smoothly on any device.
Summary
- The carousel container acts like a picture frame with hidden overflow to keep only one image visible at a time.
- Flexbox layout aligns the images in a single horizontal row so they can slide smoothly side by side.
- CSS transitions handle the animation smoothing out the movement whenever the active slide changes.
- JavaScript calculates pixel offsets using a track translation method to shift images into view when buttons are clicked.
- Modular enhancements like autoplay and swipe support can be layered on top of this core foundation.
What is a carousel?
A carousel, or slider, is a common web component that displays multiple images in the same screen area. It allows users to move between items using previous and next buttons, much like flipping through physical photo slides.
Step 1: HTML structure
Step 2: CSS styling
.carousel-container { position: relative; overflow: hidden; max-width: 600px; }
.carousel-track { display: flex; transition: transform .4s ease; }
.carousel-slide { min-width: 100%; }
.carousel-slide img { width: 100%; display: block; }
.carousel-btn { position: absolute; top: 50%; transform: translateY(-50%); }
.prev { left: 10px; }
.next { right: 10px; }Step 3: JavaScript
const track = document.querySelector('.carousel-track');
const slides = document.querySelectorAll('.carousel-slide');
let index = 0;
function update() {
track.style.transform = 'translateX(' + (-index * 100) + '%)';
}
document.querySelector('.next').addEventListener('click', () => {
index = (index + 1) % slides.length;
update();
});
document.querySelector('.prev').addEventListener('click', () => {
index = (index - 1 + slides.length) % slides.length;
update();
});Next steps
- Dots indicators
- Autoplay
- Swipe support