How to make a carousel in HTML CSS
Create a spinning carousel using HTML & CSS with an example: learn to build a modern-looking rotating carousel with images, text, and buttons.
Creating a Carousel with HTML & CSS
Creating a carousel (slideshow) with HTML & CSS requires a few steps. First, you need to create a container for the carousel, and then add the images and the navigation elements.HTML Structure
The HTML structure for the carousel is quite simple. You need to create an unordered list with all the images, and then wrap it in a <div>
element, which will act as the carousel container:
<div class="carousel">
<ul>
<li><img src="image1.jpg"></li>
<li><img src="image2.jpg"></li>
<li><img src="image3.jpg"></li>
<li><img src="image4.jpg"></li>
</ul>
</div>
CSS Styling
To style the carousel, we will use CSS. First, we need to set the container to be position: relative;
, so that the elements inside it are positioned relatively to the container:
.carousel {
position: relative;
}
Then, we will set the <ul>
element to be position: absolute;
and give it a width equal to the width of all the images added together:
.carousel ul {
position: absolute;
width: 400%;
}
Next, we need to set the <li>
elements to be float: left;
and give them a width equal to the width of the images:
.carousel li {
float: left;
width: 25%;
}
Finally, we will set the <img>
elements to be width: 100%;
so that they are displayed properly:
.carousel img {
width: 100%;
}
Adding Navigation
To add navigation to the carousel, we will use JavaScript. We will add two buttons - one for moving to the previous image, and one for moving to the next image. We will use the following HTML structure for the navigation elements:
<div class="carousel-nav">
<a href="#" class="prev">«</a>
<a href="#" class="next">»</a>
</div>
And then we will use the following JavaScript code to add the click handlers for the navigation elements:
$('.carousel-nav .prev').on('click', function(e) {
e.preventDefault();
// Previous slide code
});
$('.carousel-nav .next').on('click', function(e) {
e.preventDefault();
// Next slide code
});
That's it! You now have a working carousel with HTML & CSS.