I need to display a simple grid with square images. I was surprised to find out that it doesn't work properly when images are direct children of the grid. Images get too large, overlapping each other.
.grid {
display: grid;
gap: 10px;
grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
}
img {
aspect-ratio: 1 / 1;
background-color: orange;
object-fit: contain;
}
<div class="grid">
<img src="https://placehold.co/1920x1080">
<img src="https://placehold.co/1920x1080">
<img src="https://placehold.co/1920x1080">
<img src="https://placehold.co/1920x1080">
<img src="https://placehold.co/1920x1080">
<img src="https://placehold.co/1920x1080">
<img src="https://placehold.co/1920x1080">
<img src="https://placehold.co/1920x1080">
</div>
It works correctly if I apply width: 100%
and height: 100%
to img
, but I'm trying to understand why.
Is there some additional way of handling image sizes inside the grid? Why do they require explicit dimensions when the grid should already instruct them of such?
Why do they require explicit dimensions when the grid should already instruct them of such?
Where does the grid provide these instructions? It doesn't.
Your rule grid-template-columns: repeat(auto-fit, minmax(400px, 1fr))
sets up the columns. It doesn't apply to the content inside those columns.
Without adding width: 100%
to the images, they compute to their intrinsic size, which in this case is 1920 x 1080.
As a general practice in HTML/CSS, add img { width: 100%; height: auto }
to prevent images from overflowing their containers.