How to Create a Modal Image Gallery Lightbox With CSS and JavaScript

Modal image galleries are an essential component for many websites and applications.

They are used to display images and videos in a lightbox style popup that overlays on top of the page content.

A modal image gallery lightbox is a perfect solution to display high-resolution images without taking up too much space on your website or application.

In this tutorial, we will be showing you how to create a modal image gallery lightbox using CSS and JavaScript.


Step 1: HTML Markup

The first step to create a modal image gallery lightbox is to create the HTML markup.

We will use an unordered list to display the images and a link tag to trigger the lightbox.

<ul class="modal-gallery">
  <li>
    <a href="image1.jpg" data-lightbox="gallery">
      <img src="image1-thumbnail.jpg" alt="Image 1">
    </a>
  </li>
  <li>
    <a href="image2.jpg" data-lightbox="gallery">
      <img src="image2-thumbnail.jpg" alt="Image 2">
    </a>
  </li>
  <!-- add more list items for additional images -->
</ul>

Step 2: CSS Styles

In this step, we will style the modal lightbox using CSS.

We will be using CSS to position and size the lightbox, add a background overlay, and style the close button.

.modal-lightbox {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.8);
z-index: 9999;
display: flex;
align-items: center;
justify-content: center;
}

.modal-content {
max-width: 80%;
max-height: 80%;
background-color: #fff;
border-radius: 10px;
box-shadow: 0px 0px 10px #000;
overflow: auto;
}

.modal-close {
position: absolute;
top: 20px;
right: 20px;
font-size: 36px;
color: #fff;
cursor: pointer;
}

Step 3: JavaScript Code

Finally, we will add the JavaScript code to toggle the lightbox.

We will be using the addEventListener method to listen for the click event on the links and then show or hide the lightbox accordingly.

const modalLinks = document.querySelectorAll('.modal-gallery a');
const modalLightbox = document.querySelector('.modal-lightbox');
const modalContent = document.querySelector('.modal-content');
const modalClose = document.querySelector('.modal-close');

modalLinks.forEach(link => {
link.addEventListener('click', e => {
e.preventDefault();
const imageSrc = link.getAttribute('href');
modalContent.innerHTML = `<img src="${imageSrc}" alt="Image">`;
modalLightbox.style.display = 'flex';
});
});

modalClose.addEventListener('click', () => {
modalLightbox.style.display = 'none';
});

Conclusion

And that’s it! You now have a fully functional modal image gallery lightbox that can be used to display images and videos in a popup overlay.

With CSS and JavaScript, you have complete control over the styling and functionality of the lightbox, so you can make it fit seamlessly with your website or application.

If you have any questions or feedback, please feel free to leave a comment below.