DEV Community

Cover image for Creating an Image Slider with HTML, CSS, and JavaScript
Eric Hu
Eric Hu

Posted on • Originally published at ericsdevblog.com

Creating an Image Slider with HTML, CSS, and JavaScript

In this article, we are going to discuss how to build an image slider using HTML, CSS, and JavaScript. I will demonstrate two different ways to create the slider, one opacity based and the other transform based.

📧 Subscribe to my newsletter to get the source code for FREE!

Creating HTML

Let's first start with the HTML code:

<div class="slider">
  <div class="slide">
    <img src="images/1.jpg" alt="demo image" />
  </div>
  <div class="slide">
    <img src="images/2.jpg" alt="demo image" />
  </div>
  . . .
  <a class="prev" onclick="prevSlide()">&lt;</a>
  <a class="next" onclick="nextSlide()">&gt;</a>
</div>
Enter fullscreen mode Exit fullscreen mode
  • .slider act as the container for the entire image slider.
  • Individual slide is enclosed in a .slide container along with the image.
  • The slider navigation is controlled by two links, .prev and .next.

We also have the onclick event listener set up for the navigation links, and when they are clicked, the corresponding JavaScript functions will be activated.

Adding styles

For easier styling of elements, it is recommended to remove the default paddings and margins of all elements, and set box-sizing to border-box. This allows the elements to be sized based on their border-box dimensions rather than content-box.

* {
  padding: 0px;
  margin: 0px;
  box-sizing: border-box;
}
Enter fullscreen mode Exit fullscreen mode

And then add the styles for the .slider.

.slider {
  width: 500px;
  height: 300px;
  margin: auto;
  overflow: hidden;
  transform: translateY(50%);
}
Enter fullscreen mode Exit fullscreen mode

As well as individual .slide.

.slide {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
}

img {
  width: 100%;
  height: auto;
}
Enter fullscreen mode Exit fullscreen mode

The highlighted lines are used to center .slide inside the .slider container. For details on how to center a <div>, please refer to the linked article.

Lastly, we'll also place the navigation links on the left and right side of the .slider container.

.prev,
.next {
  cursor: pointer;
  background-color: #333;
  color: #fff;
  padding: 10px 20px;
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  text-decoration: none;
}

.prev {
  left: 0;
}

.next {
  right: 0;
}
Enter fullscreen mode Exit fullscreen mode

Here is a detailed tutorial on how to place and arrange content using CSS if you need more assistance.

Adding JavaScript code

Now, let's take a closer look at the styles for each individual .slide.

.slide {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
}
Enter fullscreen mode Exit fullscreen mode

By using the absolute position, we placed all individual .slides in one location, stacked on top of each other. You can verify that using the developer tools in your browser.

slide stack

To reveal the image underneath, all we need to do is setting the opacity of the current slide to 100, while setting the opacity of all other slides to 0. And to achieve the slideshow effect, we can write our JavaScript code so that whenever a navigation link is clicked, the "current slide" adjusts accordingly.

We'll start by setting the opacity of all slides to 0 by default.

.slide {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);

  opacity: 0;
  transition: opacity 1s ease;
}
Enter fullscreen mode Exit fullscreen mode

And then add the following JavaScript code.

const slides = document.querySelectorAll(".slide");
let currentSlide = 0;

function showSlide(index) {
  slides.forEach((slide, i) => {
    if (i === index) {
      slide.style.opacity = 100;
    } else {
      slide.style.opacity = 0;
    }
  });
}

function nextSlide() {
  currentSlide = (currentSlide + 1) % slides.length;
  showSlide(currentSlide);
}

function prevSlide() {
  currentSlide = (currentSlide - 1 + slides.length) % slides.length;
  showSlide(currentSlide);
}

showSlide(currentSlide);
Enter fullscreen mode Exit fullscreen mode

Line 1 selects all .slides, and assigns them to the variable slides.

Line 2 initiates the variable currentSlide to be 0, which points to the first slide in the image slider.

Now, let's take a look at the nextSlide() function.

function nextSlide() {
  currentSlide = (currentSlide + 1) % slides.length;
  showSlide(currentSlide);
}
Enter fullscreen mode Exit fullscreen mode

In this case, slides.length gives the total number of slides in the slider, and when this function is executed (by clicking the .next link), the currentSlide will be adjusted accordingly.

For example, when the function is executed the first time, assuming there are 5 slides in total:

currentSlide = (0 + 1) % 5 = 1
Enter fullscreen mode Exit fullscreen mode

But when it is executed the fifth time, currentSlide will reset back to 0.

currentSlide = (4 + 1) % 5 = 0
Enter fullscreen mode Exit fullscreen mode

The prevSlide() function works similarly.

function prevSlide() {
  currentSlide = (currentSlide - 1 + slides.length) % slides.length;
  showSlide(currentSlide);
}
Enter fullscreen mode Exit fullscreen mode

When currentSlide is 4, which points to the fifth slide:

currentSlide = (4 - 1 + 5) % 5 = 3
Enter fullscreen mode Exit fullscreen mode

When currentSlide is 0, which points to the first slide:

currentSlide = (0 - 1 + 5) % 5 = 4
Enter fullscreen mode Exit fullscreen mode

The currentSlide variable will then be passed to the showSlide() function as the index.

function showSlide(index) {
  slides.forEach((slide, i) => {
    if (i === index) {
      slide.style.opacity = 100;
    } else {
      slide.style.opacity = 0;
    }
  });
}
Enter fullscreen mode Exit fullscreen mode

This function iterates over all slides stored in slides, and if the iteration index (i) matches the currentSlide index (index), then that slide will have its opacity set to 100. If not, its opacity will be 0.

This will be the final result ⬇️

opacity transition

Sliding with CSS transform

We called it an image slider, but as you can see from the final result, there is not much sliding because the transition is based on opacity. How can we adjust our code so that when the navigation link is clicked, the image actually slides over to the next?

transform transition

There are two alterations you must make. First, the .slides must be arranged horizontally behind the .slider container, instead of stacked on top of each other. You can think of the .slider container as a window. Every time a link is clicked, the .slides get shifted left or right to reveal the previous or the next image.

.slider {
  width: 500px;
  height: 300px;
  margin: auto;
  overflow: hidden;
  transform: translateY(50%);

  display: flex;
  align-items: center;
}

.slide {
  flex: 0 0 100%;
  transition: transform 1s ease;
}
Enter fullscreen mode Exit fullscreen mode

We are using a flex layout to achieve this effect. flex: 0 0 100% set the width of each .slide to be 100% of the .slider.

Next, adjust the showSlide() function.

function showSlide(index) {
  slides.forEach((slide, i) => {
    const slideWidth = slide.clientWidth;
    slide.style.transform = `translateX(-${index * slideWidth}px)`;
  });
}
Enter fullscreen mode Exit fullscreen mode

Again, assuming there are five slides in total, and each slide is 500px wide. When index is 3, index * slideWidth would be 1500, and translateX(-1500px) will shift all .slides to the left by 1500 pixels, revealing the fourth image.

Conclusion

In this article, we demonstrated two ways to build an image slider, one opacity-based, and the other transform-based. I hope this article has been helpful to you. If you need more assistance regarding HTML and CSS, check out my course HTML & CSS: A Practical Guide.

That's all for this article. Happy coding!

Here are some of my other articles if you are interested:

Top comments (0)