<!DOCTYPE html>
<html>
<head>
<title>Carousel Example</title>
<style>
.carousel {
width: 300px;
height: 200px;
overflow: hidden;
position: relative;
}
.carousel-inner {
width: 100%;
height: 100%;
display: flex;
transition: transform 0.5s;
}
.carousel-slide {
width: 100%;
height: 100%;
flex-shrink: 0;
display: flex;
align-items: center;
justify-content: center;
}
</style>
</head>
<body>
<div class="carousel">
<div class="carousel-inner">
<div class="carousel-slide" style="background-color: red;"><h2>Slide 1</h2></div>
<div class="carousel-slide" style="background-color: green;"><h2>Slide 2</h2></div>
<div class="carousel-slide" style="background-color: blue;"><h2>Slide 3</h2></div>
</div>
</div>
<script>
const carousel = document.querySelector('.carousel');
const carouselInner = carousel.querySelector('.carousel-inner');
const slides = carouselInner.querySelectorAll('.carousel-slide');
const slideWidth = slides[0].offsetWidth;
let currentIndex = 0;
function goToSlide(index) {
carouselInner.style.transform = `translateX(-${index * slideWidth}px)`;
currentIndex = index;
}
function nextSlide() {
if (currentIndex === slides.length - 1) {
goToSlide(0);
} else {
goToSlide(currentIndex + 1);
}
}
setInterval(nextSlide, 2000);
</script>
</body>
</html>