Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Images scaling incorrectly in grid

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading