iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

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

BehaviourWhy it works
Responsive without media queriesThe grid reflows when the viewport shrinks — fewer columns automatically.
No cropped imagesobject-fit: cover fills the cell without squashing.
Consistent aspect ratioaspect-ratio: 4/3 locks the shape regardless of source image size.
No layout shiftSizes 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 &raquo;</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)); }

Test yourself

Q1. Which value of `grid-template-columns` produces as many columns as fit, each at least 220px?
Q2. Which property prevents images being squashed in fixed-size cells?
Q3. A gallery built with auto-fill + minmax is responsive because…

Discussion

Loading…