首页 > 解决方案 > 调整 2:1 图像的大小以放入 1:1 div

问题描述

只想让所有产品图片使用相同的 1:1 响应区域。问题是,如果图像是 2:1,它使用的空间比预期的 (1:1) 多。如何使用 css 调整它的大小以显示这样的内容?(第一个例子)

当前设置:

max-width: 100%;
width: 100%;
height: auto;
max-height: 100%;
margin: 0 auto;

标签: cssimage-resizing

解决方案


您可以使用它object-fit:cover;来覆盖图像所在的整个容器。在下面的示例中,我加载了一个 200x100 像素的图像,并将其包含在一个 100x100 像素的区域中。

请注意,IE 不支持此功能:https ://caniuse.com/#search=object-fit

#product {
  width:100px;
  height:100px;
}

#product img {
  object-fit:cover;
  width:100%;
  height:100%;
}
<div id="product">
  <img src="http://placehold.it/200x100&text=productimage">
</div>


推荐阅读