【发布时间】:2017-01-24 09:21:39
【问题描述】:
我正在尝试找到一个解决方案,而不必使用background-image,但能够使用内联<img>。
我想这样做,如果图像容器的尺寸与图像不同,图像仍然会填充容器的 width 和 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;
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>
【问题讨论】: