Image gallery with captions and lightbox
by Génesis García Morilla
HTML
<section></section>
<div id="full" class="hide"><img></div>
CSS
body {
font-family: Roboto, sans-serif;
background-color: #e3e4e5;
}
section {
display: flex;
justify-content: center;
flex-wrap: wrap;
}
figure {
display: flex;
flex-flow: column;
padding: 12px 17px;
background-color: white;
}
figure > img {
width: 255px;
height: 150px;
text-align: center;
line-height: 150px;
}
figure > img:hover {
cursor: pointer;
opacity: 0.7;
}
figcaption {
padding-top: 8px;
text-align: left;
}
#full {
position: fixed;
z-index: 1;
left: 0;
top: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.9);
}
#full:hover {
cursor: pointer;
}
#full > img {
display: flex;
margin: auto;
width: 100%;
height: 100%;
max-width: 1024px;
object-fit: contain;
animation-name: zoom;
animation-duration: 0.5s;
}
@keyframes zoom {
from { transform: scale(0); }
to { transform: scale(1); }
}
.hide {
display: none;
}
JavaScript
const images = ['tfFaE9N', 'td2y5xn', 'OYIHgN8', 'dMobJqL']
// Figures with images and captions
document.querySelector('section').innerHTML =
images.reduce((html, img) => html +=
`<figure>
<img src="https://i.imgur.com/${img}.png">
<figcaption>Example text</figcaption>
</figure>`, '')
// Click on image to maximize it
document.querySelectorAll('img')
.forEach($img => $img.onclick = () => {
const $full = document.querySelector('#full')
$full.classList.remove('hide')
$full.querySelector('img').src = $img.src
$full.onclick = () => $full.classList.add('hide')
})