Weekly Code Quickies podcast

Creating a CSS-Only Image Carousel

0:00
19:12
Spola tillbaka 15 sekunder
Spola framåt 15 sekunder

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.

Image Carousel (CSS Only)

CSS Styling

Next, we will add the CSS to style our carousel and create the animation.

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%); } }

Explanation

* HTML Structure: We have a container div with the class carousel that holds another div with the class carousel-slide. Inside the carousel-slide div, we have multiple img 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.



Get full access to Norbert’s Web Dev School at norbertbmwebdev.substack.com/subscribe

Fler avsnitt från "Weekly Code Quickies"