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
- Create a container with
display: grid. - Set
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)). - Add
gapfor spacing. - Ensure images use
width: 100%andheight: autoorobject-fit: coverinside 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-fillinstead ofauto-fitif you want empty tracks to remain when there are few items. - Combine with
aspect-ratiofor uniform image proportions without fixed heights. - Add
loading="lazy"to images for performance.