📌 What is a Lightbox?
A lightbox allows users to:
👉 click an image
👉 view it in a full-screen modal
Used in:
galleries
portfolios
e-commerce sites
1️⃣ Basic HTML structure
<div class="gallery">
<img src="img1.jpg" class="lightbox-img">
<img src="img2.jpg" class="lightbox-img">
<img src="img3.jpg" class="lightbox-img">
</div>
<!-- Lightbox modal -->
<div id="lightbox" class="lightbox">
<span class="close">×</span>
<img class="lightbox-content" id="lightbox-img">
</div>
2️⃣ CSS styling
.lightbox {
display: none;
position: fixed;
z-index: 999;
padding-top: 50px;
left: 0;
top: 0;
width: 100%;
height: 100%;
background: rgba(0,0,0,0.9);
}
.lightbox-content {
margin: auto;
display: block;
max-width: 80%;
max-height: 80%;
}
.close {
position: absolute;
top: 20px;
right: 40px;
color: white;
font-size: 40px;
cursor: pointer;
}
3️⃣ JavaScript logic
<script>
const images = document.querySelectorAll('.lightbox-img');
const lightbox = document.getElementById('lightbox');
const lightboxImg = document.getElementById('lightbox-img');
const closeBtn = document.querySelector('.close');
// Open modal
images.forEach(img => {
img.addEventListener('click', () => {
lightbox.style.display = 'block';
lightboxImg.src = img.src;
});
});
// Close modal
closeBtn.addEventListener('click', () => {
lightbox.style.display = 'none';
});
// Close when clicking outside image
lightbox.addEventListener('click', (e) => {
if (e.target !== lightboxImg) {
lightbox.style.display = 'none';
}
});
</script>
🔥 Key Features
click to enlarge image
full-screen modal
easy close interaction
✨ UX Improvements
✔ Add animation
.lightbox-content {
animation: zoom 0.3s ease;
}
@keyframes zoom {
from {transform: scale(0.8);}
to {transform: scale(1);}
}
✔ Add cursor pointer
.lightbox-img {
cursor: pointer;
}
🔐 Performance Tip
Use lazy loading:
<img src="img.jpg" loading="lazy">
✅ Summary
To create a lightbox:
create modal structure
style with CSS
add click event
handle open/close
🚀 Next Step
You can extend this by:
next / previous buttons
keyboard navigation
image captions
zoom in/out
Hope this helps 🚀
Login with Google