CSS Image Gallery

An image gallery arranges thumbnails in a tidy, responsive grid that reflows to fit any screen width.

A gallery is really just a set of images laid out with consistent spacing. CSS Grid is the cleanest tool for the job because it can create as many columns as fit and wrap the rest onto new rows automatically.

A Responsive Grid Gallery

The combination of <repeat()>, <auto-fit>, and <minmax()> tells the browser to fit as many columns as it can while keeping each one at least 150px wide. See CSS Grid for a deeper look at these functions.

Auto-fitting columns

<!DOCTYPE html>
<html>
<head>
<style>
.gallery {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
  gap: 10px;
}
</style>
</head>
<body>

<div class="gallery">
  <img src="mountain.jpg" alt="Mountain view" width="200" height="140">
  <img src="beach.jpg" alt="Beach at sunset" width="200" height="140">
  <img src="forest.jpg" alt="Forest trail" width="200" height="140">
  <img src="city.jpg" alt="City skyline" width="200" height="140">
</div>

</body>
</html>

Making Images Fit Their Cells

Photos come in different shapes, so let each image fill its cell and crop neatly with <object-fit: cover>. This keeps every thumbnail the same height without squashing the picture.

Uniform thumbnails

<!DOCTYPE html>
<html>
<head>
<style>
.gallery img {
  width: 100%;
  height: 160px;
  object-fit: cover;
  border-radius: 6px;
  display: block;
}
</style>
</head>
<body>

<div class="gallery">
  <img src="mountain.jpg" alt="Mountain view">
  <img src="beach.jpg" alt="Beach at sunset">
  <img src="forest.jpg" alt="Forest trail">
</div>

</body>
</html>

Adding a Hover Effect

Zoom on hover

<!DOCTYPE html>
<html>
<head>
<style>
.gallery a {
  overflow: hidden;
  border-radius: 6px;
}

.gallery img {
  transition: transform 0.3s ease;
}

.gallery img:hover {
  transform: scale(1.08);
}
</style>
</head>
<body>

<div class="gallery">
  <a href="#"><img src="mountain.jpg" alt="Mountain view" width="150" height="150"></a>
  <a href="#"><img src="beach.jpg" alt="Beach at sunset" width="150" height="150"></a>
  <a href="#"><img src="forest.jpg" alt="Forest trail" width="150" height="150"></a>
</div>

</body>
</html>
  • Use gap instead of margins so spacing stays even at the edges
  • object-fit: cover crops to fill; object-fit: contain fits the whole image with letterboxing
  • overflow: hidden on the wrapper keeps a zoom effect from spilling outside its cell
  • Always add descriptive alt text so the gallery works for screen readers and when images fail to load

Exercise: CSS Image Gallery

Which CSS property lets a gallery image scale down proportionally to fit its container without overflowing?