How to Create a Responsive Lightbox Gallery with Thumbnails using HTML, CSS, and JavaScript

how-to-create-a-responsive-lightbox-gallery-with-thumbnails-using-html,-css,-and-javascript

In this tutorial, we’ll walk through the steps to create a responsive lightbox gallery with thumbnails using HTML, CSS, and JavaScript. A lightbox gallery allows users to view images in a larger size without leaving the current page, enhancing the user experience.

1. HTML Structure

First, let’s set up the basic HTML structure for our gallery:

html






Responsive Lightbox Gallery







2. CSS Styling (styles.css)

Next, let’s add the CSS styles to style our gallery and lightbox:

css

/* styles.css */

.gallery {
  display: flex;
  flex-wrap: wrap;
}

.thumbnails {
  flex: 1;
  display: flex;
  flex-wrap: wrap;
}

.thumbnail {
  width: 100px;
  height: 100px;
  margin: 5px;
  cursor: pointer;
}

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

.lightbox-img {
  max-width: 80%;
  max-height: 80%;
}

.close-btn {
  position: absolute;
  top: 15px;
  right: 15px;
  font-size: 30px;
  color: #fff;
  cursor: pointer;
}

3. JavaScript (script.js)

Finally, let’s add the JavaScript code to handle the gallery functionality:

javascript

// script.js

const thumbnailsContainer = document.querySelector('.thumbnails');
const lightbox = document.querySelector('.lightbox');
const lightboxImg = document.querySelector('.lightbox-img');
const closeBtn = document.querySelector('.close-btn');

// Array of image URLs
const images = [
  'image1.jpg',
  'image2.jpg',
  'image3.jpg',
  // Add more image URLs as needed
];

// Generate thumbnails
images.forEach((image, index) => {
  const thumbnail = document.createElement('img');
  thumbnail.src = image;
  thumbnail.classList.add('thumbnail');
  thumbnail.setAttribute('data-index', index);
  thumbnail.addEventListener('click', () => openLightbox(index));
  thumbnailsContainer.appendChild(thumbnail);
});

// Open lightbox
function openLightbox(index) {
  lightboxImg.src = images[index];
  lightbox.style.display = 'flex';
}

// Close lightbox
closeBtn.addEventListener('click', () => {
  lightbox.style.display = 'none';
});

Summary

In this tutorial, we’ve created a responsive lightbox gallery with thumbnails using HTML, CSS, and JavaScript. Users can click on thumbnails to view larger images in a lightbox without leaving the page, enhancing the overall user experience of the gallery.

Total
0
Shares
Leave a Reply

Your email address will not be published. Required fields are marked *

Previous Post
the-definition-of-a-fool-is-a-drowning-man-who-tries-to-keep-it-a-secret

The Definition of a Fool is a Drowning Man Who Tries to Keep It a Secret

Next Post
tune-gemini-pro-in-google-ai-studio-or-with-the-gemini-api

Tune Gemini Pro in Google AI Studio or with the Gemini API

Related Posts