Grid-Based Image Galleries
You'll learn: How to create professional image galleries that arrange photos in uniform grids or masonry-style layouts using CSS Grid's template areas and spanning techniques.
Why Grid for Image Galleries?
CSS Grid excels at creating image galleries because it handles both uniform layouts (where all images have equal size) and masonry-style layouts (where images span different numbers of rows/columns for visual interest). Think of it like arranging photos on a wall—some might be small squares, others large rectangles spanning multiple spaces.
Uniform Image Galleries
The simplest approach uses auto-fit or auto-fill with minmax() to create responsive, equal-sized image cells:
.gallery {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
gap: 1rem;
}
.gallery img {
width: 100%;
height: 100%;
object-fit: cover;
}
This creates a flexible grid where images automatically wrap to new rows as the viewport changes.
Masonry-Style Galleries with Spanning
For visual variety, you can make specific images span multiple tracks:
.gallery {
display: grid;
grid-template-columns: repeat(4, 1fr);
grid-auto-rows: 150px;
gap: 1rem;
}
.gallery-item:nth-child(3n) {
grid-column: span 2;
grid-row: span 2;
}
This pattern makes every third image twice as large, creating that Pinterest-like effect. You can also use grid-area to place featured images in specific named areas.
Making Images Fit Properly
The CSS object-fit: cover property ensures images fill their grid cells without distortion, cropping as needed while maintaining aspect ratio.
Key Takeaway: Grid-based galleries combine responsive track sizing (auto-fit, minmax()) with strategic spanning (span keyword) to create both uniform and masonry-style image layouts that adapt beautifully to any screen size.