How to build a responsive image gallery with CSS Grid

· Category: HTML & CSS

Short answer

Use repeat(auto-fit, minmax(size, 1fr)) in grid-template-columns to let CSS Grid automatically add or remove columns as the viewport changes.

Steps

  1. Create a container with display: grid.
  2. Set grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)).
  3. Add gap for spacing.
  4. Ensure images use width: 100% and height: auto or object-fit: cover inside each cell.

Example

.gallery {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 1rem;
}
.gallery img {
  width: 100%;
  height: 200px;
  object-fit: cover;
  display: block;
}
<div class="gallery">
  <img src="a.jpg" alt="..." />
  <img src="b.jpg" alt="..." />
  <img src="c.jpg" alt="..." />
</div>

Tips

  • Use auto-fill instead of auto-fit if you want empty tracks to remain when there are few items.
  • Combine with aspect-ratio for uniform image proportions without fixed heights.
  • Add loading="lazy" to images for performance.