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?