Create Responsive Image Slider with Horizontal Scroll bar using HTML CSS & JavaScript

Create Responsive Image Slider with Horizontal Scroll using HTML, CSS, & JavaScript

A responsive image slider is an interactive web component that displays multiple images in a smooth, organised carousel while automatically adapting to different screen sizes and devices. Built with HTML, CSS, and JavaScript, it can improve website navigation, highlight important visual content, and create a more engaging user experience. Responsive image slider are commonly used for hero sections, portfolios, product showcases, galleries, banners, and landing pages, making them a useful component for modern mobile-friendly web development.
Learn how to create a responsive image slider with HTML, CSS, and JavaScript while understanding the code behind its functionality.
Step-by-step guide to demonstrate this image slider by using HTML and JS
  • Let’s set up a directory with a name of your choice and then generate the essentials files within it.
  • For the primary HTML code, create a file as index.html
  • For the CSS styling, create a file Style.css
  • For JavaScript functionality, create a file script.js
  • Then finally, create a folder named Images and placed all the required images that you have downloaded inside it.

This HTML (index.html) code creates the basic structure for a responsive image slider with horizontal scroll using HTML5. The document begins with HTML5 doctype and includes the viewport meta tag to make slider work properly on different screen sizes. The page title is set to “Image Slider with Horizontal Scroll“, which is useful for SEO and browser indentification.

The code imports Google Material Symbol Rounded to display left and right navigation icons. It also connects external style.css and script.js files for styling and slider functionality. The defer attribute allows JavaScript to load without blocking the HTML page.

Inside the main container, the slider includes previous and next buttons, while the <ul> element contains ten image items. Each image uses on alt attribute, which helps search engines and improves accessibility. The scrollbar section provides a visual indicator of the current slider position. This HTML structure provides a clean foundation for building a modern responsive, and SEO-friendly image slider with CSS and JavaScript.

<!DOCTYPE html>
<!-- Coding By Coding Jasim - www.codingjasimweb.com -->
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Image Slider with Horizontal Scroll</title>
    <!-- Google Fonts Link For Icons -->
    <link
      rel="stylesheet"
      href="https://fonts.googleapis.com/css2?family=Material+Symbols+Rounded:opsz,wght,FILL,GRAD@48,400,0,0"
    />
    <link rel="stylesheet" href="style.css" />
    <script src="script.js" defer></script>
  </head>
  <body>
    <div class="container">
      <div class="slider-wrapper">
        <button id="prev-slide" class="slide-button material-symbols-rounded">
          chevron_left
        </button>
        <ul class="image-list">
          <img class="image-item" src="images/image1.jpg" alt="img-1" />
          <img class="image-item" src="images/image2.jpg" alt="img-2" />
          <img class="image-item" src="images/image3.jpg" alt="img-3" />
          <img class="image-item" src="images/image4.jpg" alt="img-4" />
          <img class="image-item" src="images/image5.jpg" alt="img-5" />
          <img class="image-item" src="images/image6.jpg" alt="img-6" />
          <img class="image-item" src="images/image7.jpg" alt="img-7" />
          <img class="image-item" src="images/image8.jpg" alt="img-8" />
          <img class="image-item" src="images/image9.jpg" alt="img-9" />
          <img class="image-item" src="images/image10.jpg" alt="img-10" />
        </ul>
        <button id="next-slide" class="slide-button material-symbols-rounded">
          chevron_right
        </button>
      </div>
      <div class="slider-scrollbar">
        <div class="scrollbar-track">
          <div class="scrollbar-thumb"></div>
        </div>
      </div>
    </div>
  </body>
</html>
Next, incorporate the following CSS codes into your style.css file to enhance the aesthetic of your image slider. This CSS code styles a responsive image slider and creates a clean, modern layout for desktop, tablet, and mobile devices. The universal selector removes default margins and padding while using box-sizing: border-box for easier element sizing.The body rule centres the image slider vertically and horizontally and adds a light background colours. The .container controls the maximum width of the slider. The .slider-wrapper provides a relative position for the navigation buttons, while previous and next buttons are style as circular controls with hover effects.The .image-list uses CSS Grid to arrange ten images in a horizontal layout. Horizontal scrolling is enabled while the default scrollbar is hidden for a cleaner interface. Each .image-items uses object-fit: cover to maintain consistent image dimension.The scrollbar provides a visual indication of slider movement. The @media query improves responsiveness on smaller screens by hiding navigation buttons, reducing image sizes and gaps, and enabling scroll snapping. 
* {
  margin: 0;padding: 0;box-sizing: border-box;
}

body {
  display: flex;align-items: center;justify-content: center;
  min-height: 100vh;background: #f1f4fd;
}
.container { max-width: 1200px; width: 95%;
}
.slider-wrapper {
  position: relative;
}
.slider-wrapper .slide-button {
  position: absolute; top: 50%; outline: none;border: none;
  height: 50px; width: 50px; z-index: 5; color: #fff;
  display: flex; cursor: pointer; font-size: 2.2rem; background: #000;
  align-items: center;justify-content: center; border-radius: 50%;
  transform: translateY(-50%);
}
.slider-wrapper .slide-button:hover {
  background: #404040;
}
.slider-wrapper .slide-button#prev-slide {
  left: -25px; display: none;
}
.slider-wrapper .slide-button#next-slide {
  right: -25px;
}
.slider-wrapper .image-list {
  display: grid;grid-template-columns: repeat(10, 1fr);
  gap: 18px; font-size: 0; list-style: none; margin-bottom: 30px;
  overflow-x: auto; scrollbar-width: none;
}
.slider-wrapper .image-list::-webkit-scrollbar {
  display: none;
}
.slider-wrapper .image-list .image-item {
  width: 325px;height: 400px; object-fit: cover;
}
.container .slider-scrollbar {
  height: 24px; width: 100%; display: flex; align-items: center;
}
.slider-scrollbar .scrollbar-track {
  background: #ccc; width: 100%; height: 4px; display: flex;
  align-items: center; border-radius: 4px; position: relative;
}
.slider-scrollbar:hover .scrollbar-track {
  height: 4px;
}
.slider-scrollbar .scrollbar-thumb {
  position: absolute; background: #000; top: 0;
  bottom: 0; width: 50%; height: 100%; cursor: grab; border-radius: inherit;
}
.slider-scrollbar .scrollbar-thumb:active {
  cursor: grabbing; height: 8px; top: -2px;
}
.slider-scrollbar .scrollbar-thumb::after {
  content: ""; position: absolute; left: 0;
  right: 0; top: -10px; bottom: -10px;
}

/* Styles for mobile and tablets */
@media only screen and (max-width: 1023px) {
  .slider-wrapper .slide-button {
    display: none !important;
  }
.slider-wrapper .image-list {
    gap: 10px; margin-bottom: 15px; scroll-snap-type: x mandatory;
  }
.slider-wrapper .image-list .image-item {
    width: 280px; height: 380px;
  }
.slider-scrollbar .scrollbar-thumb {
    width: 20%;
  }
}

Finally, as per expectation we have to add the following JavaScript code to your script.js file for necessary actions have to be take place.

This JavaScript code adds interactive functionality to the responsive image slider. The initSlider() function first selects the image list, navigation buttons, scrollbar, and draggable scrollbar thumb using querySelector() and querySelectorAll().

The code calculates the maximum horizontal scroll distance with scrollWidth and clientWidth. Users can drag the scrollbar thumb with the mouse, and the mouse event updates the thumb position and image list simultaneously. Math.max() and Math.min() keep the thumb within its valid boudaries.

The previous and next buttons use scrollBy() with smooth scrolling to move through the images. The handleSlideButtons() function automatically shows or hides navigation buttons depending on the current scroll position.

The updateScrollThumbPosition() function keeps the scrollbar thumb aligned with the image position while scrolling. A scroll event calls both update functions. Finally, resize and load events initialise the slider when the browser size changes or the page loads.

const initSlider = () => {
    const imageList = document.querySelector(".slider-wrapper .image-list");
    const slideButtons = document.querySelectorAll(".slider-wrapper .slide-button");
    const sliderScrollbar = document.querySelector(".container .slider-scrollbar");
    const scrollbarThumb = sliderScrollbar.querySelector(".scrollbar-thumb");
    const maxScrollLeft = imageList.scrollWidth - imageList.clientWidth;
    
    // thumb drag Handle Scrollbar
    scrollbarThumb.addEventListener("mousedown", (e) => {
        const startX = e.clientX;
        const thumbPosition = scrollbarThumb.offsetLeft;
        const maxThumbPosition = sliderScrollbar.getBoundingClientRect().width - scrollbarThumb.offsetWidth;
        
        // position on mouse move Update thumb
        const handleMouseMove = (e) => {
            const deltaX = e.clientX - startX;
            const newThumbPosition = thumbPosition + deltaX;

            // Ensure the scrollbar when thumb stays within bounds
            const boundedPosition = Math.max(0, Math.min(maxThumbPosition, newThumbPosition));
            const scrollPosition = (boundedPosition / maxThumbPosition) * maxScrollLeft;
            
            scrollbarThumb.style.left = `${boundedPosition}px`;
            imageList.scrollLeft = scrollPosition;
        }

        // to Remove event listeners on mouse up
        const handleMouseUp = () => {
            document.removeEventListener("mousemove", handleMouseMove);
            document.removeEventListener("mouseup", handleMouseUp);
        }

        // For drag interaction Add event listeners
        document.addEventListener("mousemove", handleMouseMove);
        document.addEventListener("mouseup", handleMouseUp);
    });

    // Slide images according to the slide button clicks
    slideButtons.forEach(button => {
        button.addEventListener("click", () => {
            const direction = button.id === "prev-slide" ? -1 : 1;
            const scrollAmount = imageList.clientWidth * direction;
            imageList.scrollBy({ left: scrollAmount, behavior: "smooth" });
        });
    });

     // Show or hide slide buttons based on scroll position
    const handleSlideButtons = () => {
        slideButtons[0].style.display = imageList.scrollLeft <= 0 ? "none" : "flex";
        slideButtons[1].style.display = imageList.scrollLeft >= maxScrollLeft ? "none" : "flex";
    }

    // Update scrollbar thumb position based on image scroll
    const updateScrollThumbPosition = () => {
        const scrollPosition = imageList.scrollLeft;
        const thumbPosition = (scrollPosition / maxScrollLeft) * (sliderScrollbar.clientWidth - scrollbarThumb.offsetWidth);
        scrollbarThumb.style.left = `${thumbPosition}px`;
    }

    // when image list scrolls then Call these two functions 
    imageList.addEventListener("scroll", () => {
        updateScrollThumbPosition();
        handleSlideButtons();
    });
}

window.addEventListener("resize", initSlider);
window.addEventListener("load", initSlider);

In conclusion, creating a responsive image slider with HTML, CSS, and JavaScript is a useful way to improve your web development skills. By following the steps in this tutorial, you can build a functional and user-friendly image slider from scratch. You can also customise its design, images, navigation buttons, animations, and responsive behaviour to match your website requirements.

Don’t hesitate to explore different transitions, styles, and functionalities to elevate your image slider to further. To advance your web development skills. I encourage you to attempt image slider with animation or simple image slider featured/available in this site.

If you face any difficulties while constructing your image slider, you can download the source code files with no cost by clicking the download button.

Download Button with Timer | CodingJasim
Scroll to Top