【问题标题】:CSS: Get inline image to use 100% of width and height of containerCSS:获取内联图像以使用容器的 100% 的宽度和高度
【发布时间】:2017-01-24 09:21:39
【问题描述】:

我正在尝试找到一个解决方案,而不必使用background-image,但能够使用内联<img>

我想这样做,如果图像容器的尺寸与图像不同,图像仍然会填充容器的 widthheight , 裁剪它必须的任何部分。

另外,如果图像的一部分小于容器,它将拉伸超过 100% 以填充容器。

在下面的示例中,我有一个巨大的图像,可以轻松填充容器的宽度和高度。容器与图像的纵横比不同,因此我最终会出现水平或垂直的空白区域。无论如何我都想填充那个容器,即使图像的一部分会被裁剪掉。

class[*='container'] {
  margin-bottom: 50px;
}
.container img {
  width: 20%;
  height: 20%;
}
.container-1 {
  background: #f0f0f0;
  width: 400px;
  height: 150px;
}
.container-1 img {
  object-fit: cover; 
  max-width: 100%;
  max-height: 100%;
}
.container-2 {
  background: #f0f0f0;
  width: 150px;
  height: 400px;
}
.container-2 img {
  object-fit: cover; 
  max-width: 100%;
  max-height: 100%;
}
<p>Original image:</p>
<div class="container">
  <img src="https://themetry.com/wp-content/uploads/pug.jpg" />
</div>

<p>Container 1:</p>

<div class="container-1">
  <img src="https://themetry.com/wp-content/uploads/pug.jpg" />
</div>

<p>Container 2:</p>

<div class="container-2">
  <img src="https://themetry.com/wp-content/uploads/pug.jpg" />
</div>

【问题讨论】:

    标签: html css


    【解决方案1】:
    .container-1 img {
        object-fit: cover;
        /* max-width: 100%; */
        /* max-height: 100%; */
        width: 100%;
        height: 100%;
    }
    

    class[*='container'] {
      margin-bottom: 50px;
    }
    .container img {
      width: 20%;
      height: 20%;
    }
    .container-1 {
      background: #f0f0f0;
      width: 400px;
      height: 150px;
    }
    .container-1 img {
      object-fit: cover;
      width: 100%;
      height: 100%;
    }
    .container-2 {
      background: #f0f0f0;
      width: 150px;
      height: 400px;
    }
    .container-2 img {
      object-fit: cover;
      width: 100%;
      height: 100%;
    }
    <p>Original image:</p>
    <div class="container">
      <img src="https://themetry.com/wp-content/uploads/pug.jpg" />
    </div>
    
    <p>Container 1:</p>
    
    <div class="container-1">
      <img src="https://themetry.com/wp-content/uploads/pug.jpg" />
    </div>
    
    <p>Container 2:</p>
    
    <div class="container-2">
      <img src="https://themetry.com/wp-content/uploads/pug.jpg" />
    </div>

    由于您已经在使用object-fit,因此我也在回答中使用了它。请记住它是not supported by IE / Edge。以下是一些解决方法:https://stackoverflow.com/a/37127590/3597276

    【讨论】:

      猜你喜欢
      • 2011-08-07
      • 2015-03-25
      • 2012-11-05
      • 2011-08-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多