Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make image fit CSS Grid

Tags:

html

css

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%;
}

enter image description here

How can I fix this?

like image 435
Unknown User Avatar asked May 26 '18 12:05

Unknown User


3 Answers

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

like image 146
Liang Lyon Avatar answered Nov 02 '22 20:11

Liang Lyon


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;
}
like image 41
MosDev Avatar answered Nov 02 '22 18:11

MosDev


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('http://link-to-your-image/image.jpg') and use background-size: cover; on the same element.

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

like image 3
Yan Avatar answered Nov 02 '22 20:11

Yan