How to make a responsive image gallery
Short answer
A grid with an automatic number of columns and square images:
<style>
.gallery { display: grid; grid-template-columns: repeat(auto-fill, minmax(100px, 1fr)); gap: 6px; }
.gallery img { width: 100%; aspect-ratio: 1; object-fit: cover; border-radius: 6px; display: block; }
</style>
<div class="gallery">
<img src="/media/photo-200x200.jpg" alt=""><img src="/media/photo-400x250.jpg" alt="">
<img src="/media/photo-600x200.jpg" alt=""><img src="/media/photo-800x500.jpg" alt="">
<img src="/media/photo-400x250.jpg" alt="">
</div>How it works
aspect-ratio: 1 makes every cell square, and object-fit: cover fills the square with the image, cropping the rest instead of stretching it. That is why photos with different proportions look like even tiles.
Other proportions
For landscapes use aspect-ratio: 4 / 3 or 16 / 9. If cropping is not acceptable, use object-fit: contain — the image fits entirely, leaving margins at the edges.
Common mistake
Without display: block a thin strip of a few pixels appears under each image: images are inline by default and sit on the text baseline. And without width: 100% the image does not shrink to the cell and overflows the grid.
Functions used in this recipe
- grid-template-columns — The number and widths of the columns of a grid.
- object-fit — How the picture of an `<img>` or `<video>` fits into the element's box.
- aspect-ratio — The ratio of width to height: the browser computes the missing dimension.
- gap — The gaps between items in flexbox and grid.