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

Rmag Breaking News

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

<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”UTF-8″>
<meta name=”viewport” content=”width=device-width, initial-scale=1.0″>
<title>Responsive Lightbox Gallery</title>
<link rel=”stylesheet” href=”styles.css”>
</head>
<body>
<div class=”gallery”>
<div class=”thumbnails”>
<!– Thumbnails will be dynamically generated here –>
</div>
<div class=”lightbox”>
<span class=”close-btn”>&times;</span>
<img src=”” alt=”Image” class=”lightbox-img”>
</div>
</div>
<script src=”script.js”></script>
</body>
</html>

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.

Leave a Reply

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