In this tutorial we will create lightbox with html, css and javascript.
HTML
<div class="container"> <div class="image_container"></div> </div> <div class="overlay"></div>
CSS
html {
box-sizing: border-box;
}
*,
*::before,
*::after {
box-sizing: inherit;
}
body {
padding: 0;
margin: 0;
background-color: #EBF0F6;
}
.container {
width: 100%;
height: 100%;
position: relative;
}
.image_container {
display: flex;
justify-content: center;
}
img {
width: 350px;
height: 350px;
cursor: pointer;
}
.lightbox {
width: 450px;
height: 450px;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
z-index: 1;
}
.overlay_style {
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.8);
position: absolute;
top: 0;
}JS
const images = [
"images/5.jpg", "images/7.jpg", "images/9.jpg"
]
const images_container = document.querySelector('.image_container');
const overlay = document.querySelector('.overlay');
images.forEach(e => {
let img = document.createElement('img');
img.src = e;
images_container.appendChild(img);
})
images_container.addEventListener('click', (e) => {
let img = document.createElement('img');
if (e.target.tagName === "IMG") {
img.src = e.target.src;
img.className = 'lightbox';
overlay.appendChild(img);
overlay.classList.add('overlay_style');
}
img.addEventListener('click', () => {
overlay.classList.remove('overlay_style');
overlay.removeChild(img)
})
overlay.addEventListener('click', () => {
overlay.classList.remove('overlay_style');
while (overlay.hasChildNodes()) {
overlay.removeChild(overlay.firstChild)
}
})
})