Table of Contents
Creating a visually appealing and responsive photo gallery is essential for modern websites. Using CSS Flexbox, you can design a flexible multi-column layout that adapts to different screen sizes. This guide will walk you through building a responsive flexbox layout for a photo gallery with captions.
Setting Up the HTML Structure
Start by creating a container element that will hold all your gallery items. Each item will include an image and a caption. Here’s a simple HTML structure:
<div class="gallery-container">
<div class="gallery-item">
<img src="photo1.jpg" alt="Photo 1">
<p class="caption">Caption for Photo 1</p>
</div>
Repeat the <div class="gallery-item"> block for each photo.
</div>
Applying Flexbox CSS
Use CSS to style the container and items. The container will be a flex container that wraps items onto multiple lines. Here’s the CSS code:
.gallery-container {
display: flex;
flex-wrap: wrap;
gap: 10px;
justify-content: center;
}
.gallery-item {
flex: 1 1 calc(33% - 20px);
display: flex;
flex-direction: column;
align-items: center;
text-align: center;
}
.gallery-item img {
max-width: 100%;
height: auto;
}
Making the Layout Responsive
To ensure the gallery looks good on all devices, add media queries to adjust the number of columns based on screen width. For example:
@media (max-width: 768px) {
.gallery-item {
flex: 1 1 calc(50% - 20px);
}
}
And for smaller screens:
@media (max-width: 480px) {
.gallery-item {
flex: 1 1 100%;
}
}
Final Tips
Remember to optimize your images for faster loading and ensure captions are descriptive. Flexbox makes it easy to create adaptable, multi-column galleries that look great on any device.