【问题标题】:Why Isn't the image filling the whole div?为什么图像没有填满整个 div?
【发布时间】:2021-03-22 16:03:53
【问题描述】:

这是我的代码的一部分。

<section id="worthGrid">
   <div class="element">
     <a href="#">
      <img src="./img/image1.jpg" alt="some text" />
     </a>
   </div>
   <div class="element">
     <a href="#">
      <img src="./img/image2.jpg" alt="some text" />
     </a>
   </div>
</section>
#worthGrid {
  display: grid;
  grid-template-columns: auto;
  grid-template-rows: 1fr 1fr;
  grid-template-areas:
    "element"
    "element";
}

.element {
  position: relative;
  text-align: center;
  background-color: grey;
}

.element img {
  object-fit: cover;
  display: block;
  width: 100%;
  height: auto;
}

第一张图片尺寸为 1200 * 700,第二张图片尺寸为 1300 * 950。第二张图片完美地填充了整个 div,但第一张图片使一些底部区域保持空白。我已将元素的背景颜色设置为灰色以检查图像是否填充它。

我几乎尝试了所有方法,但无论我做什么都没有填满整个盒子。唯一的方法,我可以强制第一个图像完全填满整个盒子,就是设置一个固定的高度,比如height: 200px

对于我的代码的其他部分,我已将元素位置设置为 relative。我想在每张图片上显示一个标题

【问题讨论】:

    标签: html css image css-grid


    【解决方案1】:

    好的,就在我准备发布这个问题时,我想到了将min-height: 100% 和链接高度设置为 100%。

    .element img {
      width: 100%;
      height: auto;
      min-height: 100%; /*How did I miss this*/
    }
    
    .element a {
      height: 100%;
    }
    

    它解决了这个问题。我不知道为什么我没有早点想到这一点。我几乎尝试了所有其他方法。

    如果有人遇到与我相同类型的问题,那就把这篇文章留在这里吧。

    【讨论】:

      猜你喜欢
      • 2014-04-15
      • 2023-03-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多