Here are the steps on how to make a CSS-only carousel:
- Create an HTML div element to wrap the carousel.
- Add a class name to the div element, such as “carousel”.
- Add the following CSS to the carousel div element:
.carousel {
display: flex;
flex-wrap: wrap;
}
- Add the images that you want to display in the carousel as child elements of the carousel div element.
- Add the following CSS to the images:
.carousel img {
width: 100%;
height: auto;
}
- Add the following CSS to the carousel div element to control the navigation:
.carousel .prev {
position: absolute;
top: 50%;
left: 0;
transform: translate(-50px, -50%);
cursor: pointer;
}
.carousel .next {
position: absolute;
top: 50%;
right: 0;
transform: translate(50px, -50%);
cursor: pointer;
}
- Add the following JavaScript to the carousel div element to handle the navigation:
const carousel = document.querySelector(".carousel");
const prevButton = document.querySelector(".carousel .prev");
const nextButton = document.querySelector(".carousel .next");
prevButton.addEventListener("click", () => {
const currentSlide = carousel.querySelector(".active");
const previousSlide = currentSlide.previousElementSibling;
if (previousSlide) {
currentSlide.classList.remove("active");
previousSlide.classList.add("active");
}
});
nextButton.addEventListener("click", () => {
const currentSlide = carousel.querySelector(".active");
const nextSlide = currentSlide.nextElementSibling;
if (nextSlide) {
currentSlide.classList.remove("active");
nextSlide.classList.add("active");
}
});
This is just a basic example of a CSS-only carousel. You can customize it to fit your needs by adding more images, changing the CSS, or adding JavaScript to handle other events, such as clicking on the images.