CSS Images Gallery || How can We create an image gallery where clicking on an image displays it in a larger box ?

Certainly! You can create an image gallery where clicking on an image displays it in a larger box. Here's an example using HTML and CSS:



HTML:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Image Gallery</title>
  <link rel="stylesheet" href="styles.css">
</head>
<body>
  <div class="image-gallery">
    <div class="image-item">
   <img src="https://th.bing.com/th/id/OIP.HxV79tFMPfBAIo0BBF-sOgHaEy?rs=1&pid=ImgDetMain" alt="Image 1" onclick="showImage('https://th.bing.com/th/id/OIP.HxV79tFMPfBAIo0BBF-sOgHaEy?rs=1&pid=ImgDetMain')" />
    </div>
    <div class="image-item">
  <img src="https://th.bing.com/th/id/OIP.HxV79tFMPfBAIo0BBF-sOgHaEy?rs=1&pid=ImgDetMain" alt="Image 2" onclick="showImage('https://th.bing.com/th/id/OIP.HxV79tFMPfBAIo0BBF-sOgHaEy?rs=1&pid=ImgDetMain')" />
    </div>
    <!-- Add more image items as needed -->
  </div>

  <div class="image-modal" id="imageModal">
    <span class="close" onclick="closeModal()">&times;</span>
    <img class="modal-content" id="modalImage">
  </div>

  <script>
    function showImage(imageSrc) {
      document.getElementById('modalImage').src = imageSrc;
      document.getElementById('imageModal').style.display = 'block';
    }

    function closeModal() {
      document.getElementById('imageModal').style.display = 'none';
    }
  </script>
</body>
</html>      
       
      
    


CSS (styles.css):

body {
  margin: 0;
  font-family: Arial, sans-serif;
  background-color: #f0f0f0;
}

.image-gallery {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
}

.image-item {
  margin: 10px;
  cursor: pointer;
}

.image-item img {
  width: 150px;
  height: 100px;
  object-fit: cover;
}

.image-modal {
  display: none;
  position: fixed;
  z-index: 1;
  padding-top: 50px;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.9);
}

.modal-content {
  margin: auto;
  display: block;
  max-width: 80%;
  max-height: 80%;
}

.close {
  color: #fff;
  font-size: 40px;
  font-weight: bold;
  position: absolute;
  top: 10px;
  right: 20px;
  cursor: pointer;
}         


This code creates a simple image gallery with two images (you can add more by replicating the `.image-item` structure and adjusting the image sources). When you click on an image, it opens in a larger modal box, and you can close it by clicking the close (×) button. Replace `"image1.jpg"` and `"image2.jpg"` with your actual image URLs to display your images in the gallery. Adjust the styling and layout as needed to fit your design preferences.

Post a Comment

If you have any doubts, please let me know

Previous Post Next Post