CSS
Build a Responsive Image Gallery with Flexbox and Gaps
Develop an adaptable image gallery that uses Flexbox for wrapping items, maintaining consistent gaps, and adjusting responsively across different screen sizes.
/* HTML */
<div class="image-gallery">
<div class="gallery-item"><img src="https://via.placeholder.com/300x200/FF5733/FFFFFF?text=Image+1" alt="Image 1"></div>
<div class="gallery-item"><img src="https://via.placeholder.com/300x200/33FF57/FFFFFF?text=Image+2" alt="Image 2"></div>
<div class="gallery-item"><img src="https://via.placeholder.com/300x200/3357FF/FFFFFF?text=Image+3" alt="Image 3"></div>
<div class="gallery-item"><img src="https://via.placeholder.com/300x200/FF33A1/FFFFFF?text=Image+4" alt="Image 4"></div>
<div class="gallery-item"><img src="https://via.placeholder.com/300x200/57FF33/FFFFFF?text=Image+5" alt="Image 5"></div>
<div class="gallery-item"><img src="https://via.placeholder.com/300x200/A133FF/FFFFFF?text=Image+6" alt="Image 6"></div>
</div>
/* CSS */
.image-gallery {
display: flex;
flex-wrap: wrap; /* Allow items to wrap to the next line */
gap: 20px; /* Consistent spacing between items and rows */
justify-content: center; /* Center items when they don't fill a full row */
padding: 20px;
max-width: 1200px;
margin: 0 auto;
border: 2px dashed #ff8c00; /* For visualization */
}
.gallery-item {
/* flex-basis: Sets the initial size of the flex item. calc() adjusts for gaps. */
/* 3 items per row: (100% - (N-1)*gap) / N = 33.33% - (2*20px)/3 = 33.33% - 13.33px */
flex: 1 1 calc(33.33% - 13.33px);
box-sizing: border-box; /* Include padding/border in width calculation */
border: 1px solid #ff8c00;
overflow: hidden; /* For img object-fit to work correctly */
}
.gallery-item img {
display: block;
width: 100%;
height: 200px; /* Fixed height for image aspect ratio */
object-fit: cover; /* Ensures images cover the area without distortion */
}
/* Responsive adjustments */
@media (max-width: 768px) {
.gallery-item {
/* 2 items per row: (100% - (N-1)*gap) / N = 50% - (1*20px)/2 = 50% - 10px */
flex: 1 1 calc(50% - 10px); /* 2 items per row on medium screens */
}
}
@media (max-width: 480px) {
.gallery-item {
flex: 1 1 100%; /* 1 item per row on small screens */
}
}
How it works: This snippet creates a responsive image gallery using Flexbox, focusing on `flex-wrap` and the `gap` property for consistent spacing. By setting `display: flex` and `flex-wrap: wrap` on the container, items automatically move to the next line when space runs out. The `gap` property provides uniform horizontal and vertical spacing between items. Each `gallery-item` uses `flex: 1 1 calc(...)` to calculate its initial width, allowing it to grow and shrink while maintaining responsiveness. Media queries further adjust the number of items per row based on screen size, creating a fluid and aesthetically pleasing layout without complex calculations for margins.