Image Gallery — Adaptive Column Count
Adjust an image gallery's column count from 2 to 6 columns based on container width using stacked @container min-width rules for responsive masonry-style layouts.
Detailed Explanation
Galleries That Use Every Pixel
A gallery is one of the few components where you genuinely want to maximize column count to show as many thumbnails as possible. Container queries let the gallery decide column count based on its host width, not the viewport.
Stacked Breakpoints
.gallery-host {
container-type: inline-size;
}
.gallery {
display: grid;
grid-template-columns: repeat(2, 1fr);
gap: 0.5rem;
}
@container (min-width: 480px) { .gallery { grid-template-columns: repeat(3, 1fr); } }
@container (min-width: 720px) { .gallery { grid-template-columns: repeat(4, 1fr); } }
@container (min-width: 1000px) { .gallery { grid-template-columns: repeat(5, 1fr); } }
@container (min-width: 1280px) { .gallery { grid-template-columns: repeat(6, 1fr); } }
Why Not auto-fill?
grid-template-columns: repeat(auto-fill, minmax(180px, 1fr)) achieves something similar but loses precise control. Your designer wants exactly 4 columns at 720px, not "however many fit". Container queries deliver the exact column count agreed in design specs.
Square Thumbnails
.gallery img {
width: 100%;
aspect-ratio: 1;
object-fit: cover;
}
aspect-ratio: 1 keeps thumbnails square regardless of column count. Combined with object-fit: cover you avoid layout shifts when images load.
Mansory Layout Variant
For a Pinterest-style masonry layout, swap grid for CSS columns:
.gallery {
column-count: 2;
column-gap: 0.5rem;
}
@container (min-width: 720px) { .gallery { column-count: 4; } }
@container (min-width: 1000px) { .gallery { column-count: 5; } }
Lazy Loading
Pair with <img loading="lazy"> so a 6-column gallery doesn't fetch 60 images upfront.
Use Case
Use this pattern for photo galleries, product image grids, asset libraries, video thumbnail walls, and any tile-style layout where the user benefits from seeing more items at once on wider hosts.