JSFiddle - React, Tailwind, and code Playground
by jwerre
HTML
<div class="carousel-container">
<div class="carousel-slide">
<div class="carousel-item">
<h3>Slide 1</h3>
<p>This is the content of Slide 1.</p>
</div>
<div class="carousel-item">
<h3>Slide 2</h3>
<p>This is the content of Slide 2.</p>
</div>
<div class="carousel-item">
<h3>Slide 3</h3>
<p>This is the content of Slide 3.</p>
</div>
<!-- Add more carousel-item elements as needed -->
</div>
<button class="prev-btn">Prev</button>
<button class="next-btn">Next</button>
</div>
CSS
body {
margin: 0;
padding: 0;
}
.carousel-container {
width: 100%;
overflow: hidden;
position: relative;
}
.carousel-slide {
display: flex;
transition: transform 0.3s ease-in-out;
}
.carousel-item {
flex: 0 0 100%; /* Each slide occupies 100% of the container width */
height: 200px; /* Adjust the height as needed */
padding: 10px;
box-sizing: border-box;
}
.carousel-item h3 {
margin: 0;
font-size: 24px;
}
.carousel-item p {
margin: 8px 0;
}
/* Optional: Hide horizontal scrollbar */
.carousel-container::-webkit-scrollbar {
display: none;
}
/* Buttons styling */
.prev-btn, .next-btn {
position: absolute;
top: 50%;
transform: translateY(-50%);
padding: 8px 16px;
border: none;
background-color: #ccc;
cursor: pointer;
}
.prev-btn {
left: 0;
}
.next-btn {
right: 0;
}
JavaScript
const carouselSlide = document.querySelector(".carousel-slide");
const prevBtn = document.querySelector(".prev-btn");
const nextBtn = document.querySelector(".next-btn");
const slides = carouselSlide.children;
const slideWidth = slides[0].offsetWidth;
const totalSlides = slides.length;
let slideIndex = 0;
carouselSlide.style.width = `${slideWidth * totalSlides}px`;
function showSlide(index) {
const offset = -index * slideWidth;
carouselSlide.style.transform = `translateX(${offset}px)`;
}
function prevSlide() {
slideIndex--;
if (slideIndex < 0) {
slideIndex = totalSlides - 1;
}
showSlide(slideIndex);
}
function nextSlide() {
slideIndex++;
if (slideIndex >= totalSlides) {
slideIndex = 0;
}
showSlide(slideIndex);
}
prevBtn.addEventListener("click", prevSlide);
nextBtn.addEventListener("click", nextSlide);
// Show the initial slide
showSlide(slideIndex);