How to Create a Responsive Slideshow Gallery With CSS and JavaScript

Slideshow galleries are a great way to showcase a series of images on a website.

With CSS and JavaScript, you can create a responsive slideshow that adjusts to the size of the viewer’s screen.

In this tutorial, we will walk you through the steps of creating a responsive slideshow gallery using CSS and JavaScript.


CSS

First, let’s start with the CSS. We will use CSS to style the container that holds the images and the buttons that control the slideshow.

.slideshow-container {
max-width: 1000px;
position: relative;
margin: auto;
}

.mySlides {
display: none;
}

.prev, .next {
cursor: pointer;
position: absolute;
top: 50%;
width: auto;
margin-top: -22px;
padding: 16px;
color: white;
font-weight: bold;
font-size: 18px;
transition: 0.6s ease;
border-radius: 0 3px 3px 0;
user-select: none;
}

.next {
right: 0;
border-radius: 3px 0 0 3px;
}

.prev:hover, .next:hover {
background-color: rgba(0,0,0,0.8);
}

JavaScript

Next, let’s add the JavaScript that controls the slideshow.

The JavaScript will handle the display of the images and the transition between images.

var slideIndex = 1;
showSlides(slideIndex);

function plusSlides(n) {
  showSlides(slideIndex += n);
}

function currentSlide(n) {
  showSlides(slideIndex = n);
}

function showSlides(n) {
  var i;
  var slides = document.getElementsByClassName("mySlides");
  if (n > slides.length) {slideIndex = 1}
  if (n < 1) {slideIndex = slides.length}
  for (i = 0; i < slides.length; i++) {
    slides[i].style.display = "none";
  }
  slides[slideIndex-1].style.display = "block";
}

HTML

Finally, let’s add the HTML that displays the images and the buttons.

<div class="slideshow-container">

<div class="mySlides">
  <img src="img1.jpg" style="width:100%">
</div>

<div class="mySlides">
  <img src="img2.jpg" style="width:100%">
</div>

<div class="mySlides">
  <img src="img3.jpg" style="width:100%">
</div>

<a class="prev" onclick="plusSlides(-1)">&#10094;</a>
<a class="next" onclick="plusSlides(1)">&#10095;</a>

</div>

<br>

<div style="text-align:center">
  <span class="dot" onclick="currentSlides(1)"></span>
<span class="dot" onclick="currentSlides(2)"></span>
<span class="dot" onclick="currentSlides(3)"></span>
</div>

Conclusion

With just a few lines of CSS and JavaScript, you can create a responsive slideshow gallery that can be easily adapted to your website.

By using CSS, you can control the appearance of the slideshow and with JavaScript, you can control the functionality of the slideshow.

With HTML, you can display the images and buttons that make up the slideshow.

Now, you have a powerful and versatile tool for showcasing images on your website.