Lots of websites have image galleries. You’ll see them on news sites, e-commerce and blogs. They vary in size and shape. You can build them with HTML and CSS. If you want more functionality, you can add JavaScript to add a popup modal. Or Lightbox effect.
Make Your Own Gallery
- Gather 8 or more images
- Write the HTML code to structure your gallery
- Add CSS to style the gallery
- Write JavaScript to show and close the modal
1. Gather Your Images
An image gallery is incomplete without images. You can use your own photos or download Stock Photos. For this project, I used photos I downloaded for my blog. My favorite Stock Photo sites are:
2. Write the HTML Code to Structure the Gallery
Structuring the code is an important step. I used the HTML elements figure and figcaption to layout each image.
<div class="gallery">
<figure>
<img src="images/close-up-of-motherboard.jpg" alt="Motherboard" onclick="openModal(this.src)">
<figcaption class="text-center caption-text">
Motherboard
</figcaption>
</figure>
</div>
3. Add CSS to Make Look Like a Gallery
With CSS, you can arrange your images in a grid-like format. FlexBox allows you to arrange elements in a flexible grid.
.gallery {
display: flex;
flex-wrap: wrap;
gap: 1em;
}
The HTML elements made it easy to create a card design. Where the image is on top and description on the bottom half. This is also a common design pattern in image galleries.
4. Write JavaScript to Show and Close Modal
I wanted to have the image popup in a modal or Light-box when I clicked on it. A Light-box dims the rest of the page. Places the selected image on top of the page. It includes an ‘X’ button to close. I used JavaScript to open and close the modal.
function openModal(src) {
let modal = document.getElementById('modal');
let modalImg = document.getElementById('modal-img');
modal.style.display = 'flex';
modalImg.src = src;
}
function closeModal() {
let modal = document.getElementById('modal');
modal.style.display = 'none';
}
Making It Responsive
FlexBox changes the grid to a column on mobile devices. If you don’t size your images correctly, they can create performance issues. And display incorrectly on mobile devices. I used CSS to make the images fit.
img {
max-width: 100%;
vertical-align: middle;
height: auto;
}
Summary
Image gallery are simple to make. You can use them to showcase photos or open recipes and news stories. How you build them depends on the purpose that you need. This pop-up modal could be better by adding functionality to scroll through each of the images. An update for a later version.
Leave a Reply