CSS Grid Auto-Fit Image Gallery
Build a responsive gallery with repeat(auto-fit, minmax()) that never overflows, keeps captions aligned, and falls back gracefully.
Code
/* Markup contract:
<ul class="gallery">
<li class="gallery__item">
<img src="/cabin.jpg" alt="Cabin at dusk">
<h3>Cabin at dusk</h3>
<p>Two-night stay near the lake.</p>
</li>
</ul> */
.gallery {
--gallery-min: 14rem;
--gallery-gap: clamp(0.75rem, 2vw, 1.5rem);
display: grid;
grid-template-columns: repeat(auto-fit, minmax(min(100%, var(--gallery-min)), 1fr));
gap: var(--gallery-gap);
align-items: start;
margin: 0;
padding: 0;
list-style: none;
}
.gallery__item {
display: grid;
grid-template-rows: auto 1fr auto;
gap: var(--space-2, 0.5rem);
min-inline-size: 0;
padding: var(--space-3, 1rem);
border: 1px solid var(--color-border, #d4d4d8);
border-radius: var(--radius-md, 0.5rem);
background: var(--color-surface, #ffffff);
}
.gallery__item img {
inline-size: 100%;
aspect-ratio: 4 / 3;
object-fit: cover;
border-radius: calc(var(--radius-md, 0.5rem) - 0.125rem);
}
.gallery__item h3 {
margin: 0;
font-size: 1.05rem;
text-wrap: balance;
}
.gallery__item p {
margin: 0;
color: var(--color-text-muted, #52525b);
text-wrap: pretty;
}
/* Keep every card the same height when captions wrap to different lines. */
@supports (grid-template-rows: subgrid) {
.gallery__item {
grid-row: span 3;
grid-template-rows: subgrid;
}
}How it works
display: grid owns the layout: tracks are declared on the container, so children fall into place without wrapper markup.
aspect-ratio pins the box to a fixed width/height ratio, so height follows width with no padding hack.
clamp() evaluates to [min, preferred, max] — the value scales fluidly but never leaves the bounds.
object-fit decides how the media fills its box while keeping its own aspect ratio.
min() resolves to the smaller of the listed values, acting as an upper bound that still adapts.
Values that repeat across rules live in custom properties (--gallery-min, --gallery-gap, --gallery-min, --gallery-gap, --space-2), so a theme change is one edit instead of a hunt through every rule.
The rules target .gallery__item — each selector names the element it restyles, in source order.
Interactive Tools for This Topic
FAQ
- Which elements does this stylesheet target?
- The rules bind to `.gallery__item`; when two rules tie in specificity, the one written later in the file wins.
Report a problem with this exampleOpens a pre-filled issue on GitHub.