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
- A carousel shows one image inside a frame that clips the rest.
- HTML holds the track, the slides and the two buttons.
- CSS makes each slide exactly as wide as the frame.
- JavaScript only changes the track translateX.
- Dots and autoplay come after the manual swap already works.
What the page has to hide
A carousel shows one image at a time in the same rectangle. The other images stay in the HTML, lined up side by side, while a mask clips anything past the visible width. The visitor does not change pages: a click only slides that strip.
Three pieces do the work. HTML stores the strip and the buttons. CSS sets each slide width and the animation. JavaScript changes one number, the current index, and applies that offset.
Step by step
Build in this order. If a button does nothing, the bug is usually the selector or the slide width, not the index math.
- Create a container with hidden overflow and, inside it, a flexible track with one block per photo.
- Make each slide 100% of the container width and let the image fill the slide.
- Place previous and next buttons on top of the container.
- In JavaScript, start the index at zero and write a function that sets translateX to negative 100% times the index.
- On next, add 1 and wrap to zero after the last photo. On previous, go the other way.
- Check in the browser: three clicks to the right should return to the first photo, with no horizontal page scroll.
<div class='carousel'>
<div class='carousel-track'>
<div class='carousel-slide'><img src='photo-1.jpg' alt='First photo'></div>
</div>
<button type='button' class='next'>Next</button>
</div>let index = 0;
function update() {
track.style.transform = 'translateX(' + (-index * 100) + '%)';
}Common mistakes
The slide breaks when its width is not exactly the visible width, or when the script runs before the HTML exists. To complement this implementation in production environments, see our related technical analyses on Pure CSS Design System: How to Create Premium Cards and Sidebars and How to create and sign commits using GPG keys or SSH keys for authenticity.
- Put the script at the end of the body or wait for DOMContentLoaded.
- Do not give the image a fixed pixel width inside the slide.
- Write alt text for every image.
- Add dots and autoplay only after the manual click already moves the slide.
Conclusion
A carousel is a strip that moves in 100% steps. HTML lists the photos, CSS clips the overflow and JavaScript only updates the index.
Once that core is stable, dots and autoplay are just a counter on the same update function.