Make Image Fit Css Grid

I have a grid in which I position images but they doen't fill the entire space they are given.

I hope the image below illustrates the problem good enough. As we can see the top image as well as the right one don't fill the rows they are assigned to. What causes this and how can I fix it?

Code is like that:

 <section class="wrapper">
   <div class="one">
     <img class="img" src="images/lorem/ipsum.jpg" alt="">
   </div>

   <div class="two">
     <img class="img" src="images/lorem/ipsum2.jpg" alt="">
   </div>

   <div class="three">
     <img class="img" src="images/lorem/ipsum3.jpg" alt="">
   </div>
 </section>

 .wrapper {
   display: grid;
   grid-template-columns: repeat(8, 1fr);
   grid-auto-rows: minmax(150px, auto);
   grid-gap: 20px;
   height: 100vh;
 }

.one {
  grid-column: 2 / 7;
  grid-row: 1 / 3;
}

.two {
  grid-column: 2 / 5;
  grid-row: 3 / 4;
} 

.three {
  grid-column: 5 / 7;
  grid-row: 3 / 4;
}

.img {
  width: 100%;
}

How can I fix this?

5

5 Answers

add one div to wrap your image, then set image style to .img { max-width: 100%; height: auto }

2

I had a similar problem to this before , the simple solution is to set the height or width to 100% for the img elements to fill their container. Then to set the object fit property to cover for better cropping. You don't even need div containers for your images. Like this:

The grid container will take care of the positioning of the cells.

img{
width: 100%;
height: 100%;
object-fit: cover;
}

This is normal because images are preserving their aspect ratio.

A good way to solve this common problem is to set the image as a CSS-background parameter in a div in your grid instead of an <img> tag in html, such as background: url('') and use background-size: cover; on the same element.

This way, the picture will fill out all the space that is attributed to it.

2

Try background-size: 100% 100% and background-size: cover or fit

This worked for me using React with inline styles:

<div 
    style = {{
        gridArea: "image",
        backgroundImage: `url(${imageFromImports})`,
        backgroundSize: "contain",
        backgroundRepeat: "no-repeat",
        backgroundPosition: "center",
    }}
/>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Sophia Al-Mansoor

Sophia Al-Mansoor

Global Business & E-Commerce Reporter

Sophia analyzes international trade, startup ecosystems, retail transformation, and supply chain logistics for modern digital publications.

Share this article
Twitter Facebook Pinterest