Responsive Image Gallery in HTML CSS

It's crucial to emphasize the importance of responsive design in the dynamic realm of web design. Websites must have the capability to adapt to various screen sizes and devices to ensure accessibility on the web. Image galleries are a key aspect of responsive design that often requires attention. In this tutorial, we will explore the process of employing HTML and CSS to build a responsive image gallery that performs effectively across a variety of devices.

HTML Organisation

First and foremost, we will establish the HTML structure for our image gallery. Our images will be organized within an unordered list (<ul>) that is relatively straightforward.

Example

<!DOCTYPE html>

<html lang="en">

<head>

  <meta charset="UTF-8">

  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <title>Responsive Image Gallery</title>

  <link rel="stylesheet" href="styles.css">

</head>

<body>

  <div class="gallery">

    <ul>

      <li><img src="https://placehold.co/400x300/1abc9c/ffffff?text=Sample+Image" alt="Image 1"></li>

      <li><img src="https://placehold.co/400x300/1abc9c/ffffff?text=Sample+Image" alt="Image 2"></li>

      <li><img src="https://placehold.co/400x300/1abc9c/ffffff?text=Sample+Image" alt="Image 3"></li>

      <!-- Add more images as needed -->

    </ul>

  </div>

</body>

</html>

CSS Styling

Now, it's time to incorporate CSS to design our image gallery and ensure it adapts well to different screen sizes.

Example

body {

  font-family: Arial, sans-serif;

  margin: 0;

  padding: 0;

}


.gallery {

  display: flex;

  flex-wrap: wrap;

  justify-content: center;

  list-style: none;

  padding: 0;

}


.gallery li {

  margin: 10px;

}


.gallery img {

  max-width: 100%;

  height: auto;

}

Output:

When the width of the container is not enough, we can easily align and wrap the images in a row by utilizing the display: flex; property.

When there isn't enough space in the container, flex-wrap: wrap; make sure that objects wrap over to the following line.

  • Justify-content: centre;: This places the pictures in the container's horizontal centre.
  • list-style: none;: This causes the unordered list's default bulleC# Tutorials to disappear.
  • Max-width: 100%;: Guarantees that the pictures preserve their aspect ratio even when they resize proportionately to meet the width of the container.
  • Height: auto;: Maintains the aspect ratio of the pictures by automatically adjusting their height.
  • Enhancing Interactivity

While our existing setup forms a strong base for a dynamic image showcase, we can elevate user engagement by incorporating basic JavaScript functionalities.

Example

<!DOCTYPE html>

<html lang="en">

<head>

  <meta charset="UTF-8">

  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <title>Responsive Image Gallery</title>

  <link rel="stylesheet" href="styles.css">

  <script>

    document.addEventListener("DOMContentLoaded", function() {

      const images = document.querySelectorAll('.gallery img');

      
      images.forEach(image => {

        image.addEventListener('click', function() {

          images.forEach(img => img.classList.remove('active'));

          this.classList.add('active');

        });

      });

    });

  </script>

</head>

<body>

  <div class="gallery">

    <ul>

      <li><img src="https://placehold.co/400x300/1abc9c/ffffff?text=Sample+Image" alt="Image 1"></li>

      <li><img src="https://placehold.co/400x300/1abc9c/ffffff?text=Sample+Image" alt="Image 2"></li>

      <li><img src="https://placehold.co/400x300/1abc9c/ffffff?text=Sample+Image" alt="Image 3"></li>

      <!-- Add more images as needed -->

    </ul>

  </div>

</body>

</html>

JavaScript is utilized to create interactivity within our image gallery. Clicking on a picture triggers it to become an active image, while all other images are stripped of their "active" class.

By employing the forEach method, an event listener gets attached to every image within the gallery. Upon being clicked, a particular image acquires the "active" class, while other images relinquish it.

Putting the Active Image in Style

Let's modify our CSS to give the active image a distinctive style that distinguishes it from the rest.

Example

.gallery img.active {

  border: 2px solid #ff7f0e;

  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);

}

We have improved the interactive features of our image gallery by incorporating JavaScript. Allowing users to select photos by clicking on them enhances the user experience significantly. Additionally, visually distinguishing the active image helps users easily identify which picture is currently selected.

Our updated image gallery is not just more efficient but also visually appealing and user-centric due to these enhancements. You are encouraged to expand on this foundation and customize it to align with your website's specific needs. By incorporating JavaScript, we have enriched the user engagement of our image gallery. Allowing users to select photos by clicking on them enhances the overall user interaction.

It also aids in clearly indicating which image is currently selected by styling the active picture differently. Our current picture is distinctively highlighted. This enhancement has made our responsive image gallery not only more efficient but also visually appealing and user-centric. You are encouraged to expand on these enhancements and customize them to better suit the specific needs of your website.

Including Buttons for Navigation

By incorporating navigation buttons, we can elevate the user experience by providing an effortless way for users to move between the images in the gallery.

Example

<!DOCTYPE html>

<html lang="en">

<head>

  <meta charset="UTF-8">

  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <title>Responsive Image Gallery</title>

  <link rel="stylesheet" href="styles.css">

  <script>

    document.addEventListener("DOMContentLoaded", function() {

      const images = document.querySelectorAll('.gallery img');

      const prevBtn = document.querySelector('.prev-btn');

      const nextBtn = document.querySelector('.next-btn');

      let currentIndex = 0;


      function showImage(index) {

        images.forEach(image => image.classList.remove('active'));

        images[index].classList.add('active');

      }


      prevBtn.addEventListener('click', function() {

        currentIndex = (currentIndex === 0) ? images.length - 1 : currentIndex - 1;

        showImage(currentIndex);

      });


      nextBtn.addEventListener('click', function() {

        currentIndex = (currentIndex === images.length - 1) ? 0 : currentIndex + 1;

        showImage(currentIndex);

      });

    });

  </script>

</head>

<body>

  <div class="gallery">

    <button class="prev-btn">Prev</button>

    <ul>

      <li><img src="https://placehold.co/400x300/3498db/ffffff?text=Sample+Image" alt="Image 1"></li>

      <li><img src="https://placehold.co/400x300/1abc9c/ffffff?text=Sample+Image" alt="Image 2"></li>

      <li><img src="https://placehold.co/400x300/3498db/ffffff?text=Sample+Image" alt="Image 3"></li>

      <!-- Add more images as needed -->

    </ul>

    <button class="next-btn">Next</button>

  </div>

</body>

</html>

Explanation:

By utilizing JavaScript, this HTML file orchestrates an interactive image collection with navigation functionalities. Upon page loading, the designated JavaScript code is triggered to initialize an event listener. It locates all image elements within the designated gallery container and stores references to the preceding and succeeding navigation buttons.

These buttons perform corresponding functions that, upon activation, trigger the navigation within the image collection. An essential element in this mechanism is the showImage function, responsible for managing the visual presentation by toggling the "active" class among the images. This dynamic adjustment of classes showcases the presently selected image while concealing the rest, enhancing the user's ability to track their position within the gallery.

Users can easily browse through the image gallery thanks to the functionality provided by JavaScript, enhancing the navigation experience with seamless and user-friendly features. Manipulating the navigation buttons triggers a mechanism that dynamically updates the index of the displayed image, ensuring alignment between visual feedback and user actions. Moreover, the utilization of the "active" class modification enables instant modifications to the gallery layout, emphasizing the selected image while concealing others. The integration of HTML, CSS, and JavaScript leads to a responsive layout adaptable to various devices, enhancing user engagement through interactive components and elevating the visual attractiveness and usability of the picture gallery.

Designing Navigation Buttons

To enhance the visual appeal of the navigation buttons, we will implement some basic styling techniques.

Example

.gallery button {

  border: none;

  background-color: #4CAF50;

  color: white;

  padding: 10px 20px;

  text-align: center;

  text-decoration: none;

  display: inline-block;

  font-size: 16px;

  margin: 10px;

  cursor: pointer;

}


.gallery button:hover {

  background-color: #45a049;

}

Exaplaination:

The CSS rules provided below target the buttons contained within a container assigned the class "gallery". This ensures consistent appearance of the buttons within the picture gallery. The property border: none; eliminates the default border decoration on the buttons, creating a sleek interface.

By altering the background color to a pale green (#4CAF50), the background-color: #4CAF50 property enhances the button's visual prominence. The color: white; declaration changes the text color to white against a green background, ensuring optimal readability. Setting padding: 10px 20px establishes a margin around the button's content, offering appropriate spacing. With text-align: centre;, the text within the button is horizontally centered.

Additionally, setting text-decoration: none; removes the default underlining from the text, which can impact the appearance of the button. When display: inline-block; is used, the buttons act as block-level elements, allowing adjustments to the width and height attributes. A font-size of 16px; is specified to ensure optimal readability. To prevent the buttons from appearing too close to other elements, each button is surrounded by an extra 10 pixels of space. Finally, the pointer cursor changes to indicate to users that the buttons are interactive elements when hovered over.

Output:

Conclusion

Users can now effortlessly navigate through the gallery's images due to the inclusion of navigation controls. These controls enhance the usability of the image gallery by providing users with a straightforward way to engage with the content.

By combining adaptable design principles with user engagement, we've developed a dynamic photo gallery that offers enhanced interactivity and user-friendliness. This gallery seamlessly adapts to different screen dimensions and devices, ensuring a smooth user experience. You are encouraged to customize and expand on this setup to align with your specific requirements and design preferences.

Input Required

This code uses input(). Please provide values below: