我有以下代码:
#container {
background: steelblue;
width: 333px;
height: 333px;
}
picture img {
object-fit: cover;
}
<div id="container">
<picture>
<img src="http://placekitten.com/g/300/300" alt="kitten">
</picture>
</div>
如何让图片填满容器盒?
你必须在'picture'元素中使用display:flex
(与'img'的object-fit
属性一起使用)
这适用于任何大小的容器。
像这样:
#container {
background: steelblue;
width: 333px;
height: 500px;
}
picture {
width: 100%;
height: 100%;
display: flex;
}
picture img {
object-fit: cover;
height: auto;
width:100%;
}
<div id="container">
<picture>
<img src="http://placekitten.com/g/300/300" alt="kitten">
</picture>
</div>
你必须拉伸BOTH图片和img元素:
#container {
background: steelblue;
width: 333px;
height: 333px;
}
picture, img {
width: 100%;
height: 100%;
}
只需添加一个width: 100%;
到你的img。如果两者都是正方形,它将适合容器。
最简单的方法是将width
和height
添加到img
:
img {
width : 100%;
height: 100%;
}
还可以使用object-fit
CSS属性指定如何调整元素大小以适合其容器。为了保持宽高比:
object-fit: contain;
包含
替换的内容被缩放以在适合元素的内容框时保持其纵横比。