Image Viewer

In this tutorial, you will learn how to create an image viewer popup with CSS and JavaScript. When an image is clicked, a popup opens with a full view of the image clicked. Watch the video below for a detailed tutorial.


HTML

<body>
    <div class="container">
        <img src="https://images.unsplash.com/photo-1636328417187-f7ba71b86824?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1632&q=80" alt="Free image from unsplash" width="300" height="200" class="image">
        <img src="https://images.unsplash.com/photo-1447752875215-b2761acb3c5d?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1170&q=80" alt="Free image from unsplash" width="300" height="200" class="image">
        <img src="https://images.unsplash.com/photo-1510784722466-f2aa9c52fff6?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1170&q=80" alt="Free image from unsplash" width="300" height="200" class="image">
    </div>

    <div id="image-viewer">
        <div>
            <span id="close">&times;</span>
            <img id="full-image">
        </div>
    </div>

    <script>
        document.querySelectorAll('.image').forEach(image => {
            image.addEventListener('click', event => {
                document.getElementById('full-image').setAttribute('src', image.getAttribute('src'));
                document.getElementById('image-viewer').style.display = 'block';
            })
        })

        document.getElementById('close').addEventListener('click', function() {
            document.getElementById('image-viewer').style.display = 'none';
        })
    </script>
</body>

CSS

body {
  margin: 0;
  background-color: #2e3537;
  padding: 1em;
}

img {
  border-radius: 5px;
}

.container {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.container .image {
  cursor: pointer;
  object-fit: cover;
  transition: 0.3s;
}

.container .image:hover {
  opacity: 0.8;
}

#image-viewer {
  display: none;
  z-index: 999;
}

#image-viewer div {
  position: fixed;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0,0,0,0.7);
  overflow: auto;
  display: flex;
  justify-content: center;
  align-items: center;
}

#image-viewer div img {
  display: block;
  width: 80%;
  max-width: 800px;
  animation: showImage 0.5s;
}

@keyframes  showImage {
  from {
    transform: scale(0);
  }
  to {
    transform: scale(1);
  }
}

#close {
  position: absolute;
  top: 15px;
  right: 35px;
  color: white;
  font-size: 30px;
  transition: 0.3s;
  cursor: pointer;
}

#close:hover, #close:focus {
  opacity: 0.8;
}

@media  screen and (max-width: 700px) {
  .viewer {
    width: 100%;
  }
}