使图像适合CSS网格

时间:2018-05-26 12:12:04

标签: html css css-grid

我有一个网格,我在其中定位图像,但它们并没有填满它们给定的整个空间。

我希望下面的图片说明问题足够好。正如我们所看到的那样,顶部图像和右图不会填充它们所分配的行。是什么导致这种情况以及如何解决?

代码就是这样:

 <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

我该如何解决这个问题?

4 个答案:

答案 0 :(得分:2)

添加一个div来包装图像,然后将图像样式设置为 .img {   最大宽度:100%;   高度:自动 }

答案 1 :(得分:1)

这是正常的,因为图像保留了它们的宽高比。

解决此常见问题的一种好方法是将图像设置为网格中div的CSS背景参数,而不是html中的<img>标记,例如background:url('{{3 }}')并在同一元素上使用background-size: cover;

这样,图片将填充归因于它的所有空间。

答案 2 :(得分:1)

我之前也遇到过类似的问题,简单的解决方案是将 img 元素的高度或宽度设置为 100% 以填充其容器。然后将对象适合属性设置为覆盖以获得更好的裁剪。您甚至不需要图像的 div 容器。像这样:

网格容器将负责单元格的定位。

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

答案 3 :(得分:-1)

尝试背景大小:100%100%和背景大小:覆盖或适合