【问题标题】:How can I get an image to fit to the size of a grid cell?如何获得适合网格单元大小的图像?
【发布时间】:2020-07-28 07:59:34
【问题描述】:

我想将图像放置在单元格中,以便图像的大小由单元格的大小决定,而不是相反。我试过这样做:

.app-container {
  width: 100vw;
  height: 100vh;
}

.info {
  display: grid;
  min-height: 0;
}

.image-box {
  display: grid;
  min-height: 0;
}

img {
  object-fit: contain;
  width: 100%;
  height: 100%;
  grid-row: 1;
  grid-column: 1;
}
<div class="app-container">
  <div class="info">
    <div class="image-box" style="grid-row-start: 1; grid-column-start: 1;">
      <img src="https://images.unsplash.com/photo-1482003297000-b7663a1673f1?ixlib=rb-1.2.1&q=85&fm=jpg&crop=entropy&cs=srgb&ixid=eyJhcHBfaWQiOjE0NTg5fQ">
    </div>
  </div>
</div>

但图像始终以其原始大小显示并且不会缩放。我错过了什么? JSFiddle 上的完整示例here

【问题讨论】:

    标签: html css image css-grid


    【解决方案1】:

    图像在 Grid 和 Flex 布局中非常棘手。我不确定是不是因为 Grid 和 Flex 是新技术,浏览器还没有完全适应长期存在的&lt;img&gt; 标签。或者也许是别的东西。但归根结底:用 CSS3 技术处理图像很糟糕。您必须尝试不同的东西,同时在每个主流浏览器中测试每个排列,因为无法保证一致性。

    多年来我学到的一件事很有帮助,那就是永远不要将图像设为网格或弹性项目。换句话说,永远不要让图像成为容器的孩子。给图像它自己的容器,使该元素成为项目。一旦你采取了行动,很多事情往往会水到渠成。

    这是您的代码的修改版本(HTML 没有更改):

    在 Chrome、Firefox 和 Edge 中测试。

    .image-box {
      height: 50vh;
      border: 2px solid red;
      display: grid;
      grid-template-columns: 1fr 1fr 1fr;
      grid-template-rows: 1fr 1fr 1fr;
      grid-template-areas: 
        " demo1 image demo2 "
        " demo1 image demo2 "
        " demo1 image demo2 ";
    }
    
    .image-box > div:first-child {
      grid-area: demo1;
      background-color: lightgreen;
    }
    
    .image-box > div:nth-child(2) {
      grid-area: image;
      min-width: 0;
    }
    
    img {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
    
    .image-box > div:last-child {
      grid-area: demo2;
      background-color: aqua;
    }
    
    .app-container {}
    .info {}
    <div class="app-container">
      <div class="info">
        <div class="image-box">
          <div>demo item 1</div>
          <div><img src="https://images.unsplash.com/photo-1482003297000-b7663a1673f1?ixlib=rb-1.2.1&q=85&fm=jpg&crop=entropy&cs=srgb&ixid=eyJhcHBfaWQiOjE0NTg5fQ">
          </div>
          <div>demo item 2</div>
        </div>
      </div>
    </div>

    jsFiddle demo

    【讨论】:

    • 但在您的示例中,图像大小是明确指定的。是否有解决方案始终遵循网格单元的比例?如果我删除图像框高度并再次增加中心列的宽度,图像会延伸到底部
    • 这里说明了这个问题:jsfiddle.net/1vywkhoe
    • 我在您的演示中看不到图像超出底部。容器正在扩展以容纳图像(如红色边框所示)。在容器上设置高度是一种选择吗? jsfiddle.net/10x8qkun
    猜你喜欢
    • 2014-09-02
    • 1970-01-01
    • 2010-10-27
    • 2019-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-13
    • 1970-01-01
    相关资源
    最近更新 更多