Build a basic image slider with HTML and CSS

Hey, I am Ajink, and today in this blog, we’re going to build a basic image slider using HTML and CSS.

HTML Code: (image slider with HTML )

create index.html file make sure you have 3 images ready or download them from google or use local images

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="style.css">
  <title>Basic Image Slider</title>
</head>
<body>
  <div class="slider-container">
    <div class="slide">
      <img src="image1.jpg" alt="Slide 1">
    </div>
    <div class="slide">
      <img src="image2.jpg" alt="Slide 2">
    </div>
    <div class="slide">
      <img src="image3.jpg" alt="Slide 3">
    </div>
  </div>
  <script defer src="script.js"></script>
</body>
</html>

Please make sure you have valid image sources (replace “image1.jpg”, “image2.jpg”, etc., with your actual image file paths).

CSS Code : Create a style.css in same directory

body {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100vh;
  margin: 0;
  background-color: #f0f0f0;
}

.slider-container {
  position: relative;
  width: 80%;
  max-width: 600px;
  overflow: hidden;
}

.slide {
  width: 100%;
  display: none;
}

.slide img {
  width: 100%;
  height: auto;
}

Javascript : Create a script.js

document.addEventListener("DOMContentLoaded", function () {
  let currentSlide = 0;
  const slides = document.querySelectorAll(".slide");

  function showSlide(index) {
    slides.forEach((slide, i) => {
      slide.style.display = i === index ? "block" : "none";
    });
  }

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

  // Initially show the first slide
  showSlide(currentSlide);

  // Auto-advance to the next slide every 3 seconds
  setInterval(nextSlide, 3000);
});

Conclusion:

In this blog, we successfully built a basic image slider using HTML and CSS. You can customize it by adding more slides and adjusting styles. Don’t forget to subscribe to my YouTube channel at youtube.com/@ajink21 for more exciting tutorials.

Thanks for reading, and if you have any doubts, feel free to comment!

Ajink Gupta
Ajink Gupta

Ajink Gupta is a software developer from Dombivli, Maharashtra, India. He has expertise in a variety of technologies including web development, mobile app development, and blockchain. He works with languages and frameworks like JavaScript, Python, Flutter, React, and Django.

Ajink Gupta is also active on several platforms where he shares his work and engages with the community. You can find his projects and contributions on GitHub and follow his tutorials and updates on his YouTube channel​ . He also has a personal website where he showcases his portfolio and ongoing projects at ajinkgupta.vercel.app

Articles: 60