CSS Image Gallery
An image gallery is a classic CSS Grid use case. Define the columns once and drop in as many photos as you like — the grid handles the rest.
The CSS Grid recipe
CSS
.gallery {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
gap: 12px;
}
.gallery img {
width: 100%;
aspect-ratio: 4 / 3;
object-fit: cover; /* crop, never squash */
border-radius: 6px;
display: block;
}
auto-fill + minmax(220px, 1fr) means: fit as many columns as possible at 220px minimum, growing them to share leftover space.
What you get for free
| Behaviour | Why it works |
|---|---|
| Responsive without media queries | The grid reflows when the viewport shrinks — fewer columns automatically. |
| No cropped images | object-fit: cover fills the cell without squashing. |
| Consistent aspect ratio | aspect-ratio: 4/3 locks the shape regardless of source image size. |
| No layout shift | Sizes are known up-front, so CLS stays low. |
Tip: For a masonry-style "Pinterest" layout (varied heights), look at
grid-template-rows: masonry (still being shipped) or a small JS layout library.Example
Example
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: Verdana, sans-serif; }
.box { background: #04AA6D; color: #fff; padding: 20px; border-radius: 6px; }
</style>
</head>
<body>
<h1>CSS Image Gallery</h1>
<div class="box">Edit the CSS on the left, then click Run »</div>
</body>
</html>
Try it Yourself »
Exercise
Lay the gallery out as as-many-as-fit columns at 220px minimum.
.gallery { display: grid; grid-template-columns: repeat(
, minmax(220px, 1fr)); }
Hyphenated keyword, "auto-".
Discussion
Loading…