In this tutorial, we will create a simple image carousel using only HTML and CSS. This carousel will automatically cycle through images with a smooth animation effect.
HTML Structure
First, let's set up the basic HTML structure for our carousel.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Image Carousel (CSS Only)</title>
</head>
<body>
<div class="carousel">
<div class="carousel-slide">
<img src="./img/img01.jpeg" alt="Image 1" />
<img src="./img/img02.jpeg" alt="Image 2" />
<img src="./img/img03.jpeg" alt="Image 3" />
<!-- Add more images as needed -->
</div>
</div>
</body>
</html>
CSS Styling
Next, we will add the CSS to style our carousel and create the animation.
<style>
body {
display: flex;
justify-content: center;
align-items: center;
margin: auto;
height: 100vh;
background: rgb(2, 8, 91);
background: radial-gradient(
circle,
rgb(6, 14, 124) 0%,
rgba(0, 0, 0, 1) 100%
);
}
.carousel {
width: 100%;
height: 50vh;
overflow: hidden;
position: relative;
border-radius: 5px;
}
.carousel-slide {
display: flex;
width: 300%; /* Adjust based on the number of images */
animation: carousel-animation 15s infinite alternate; /* Adjust duration as needed */
}
.carousel-slide img {
width: calc(100% / 3); /* Adjust based on the number of images */
height: 100%;
object-fit: cover;
}
@keyframes carousel-animation {
/* Adjust based on the number of images */
/* 3 image animation */
0% {
transform: translateX(0);
}
33.33% {
transform: translateX(0);
}
66.66% {
transform: translateX(-33.33%);
}
100% {
transform: translateX(-66.66%);
}
}
</style>
Explanation
HTML Structure: We have a container
div
with the classcarousel
that holds anotherdiv
with the classcarousel-slide
. Inside thecarousel-slide
div, we have multipleimg
elements representing the images in the carousel.CSS Styling:
The
body
is styled to center the content and set a background gradient.The
.carousel
class styles the carousel container, setting its dimensions and overflow properties.The
.carousel-slide
class styles the slide container, setting its width to accommodate all images and applying the animation.The
.carousel-slide img
class styles the images, ensuring they fit within the carousel.The
@keyframes carousel-animation
defines the animation for the carousel, moving the images horizontally.
With this setup, you have a simple, CSS-only image carousel that cycles through images automatically. You can adjust the number of images and the animation duration as needed.
Share this post