我有以下代码:
#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>
如何使图片填充容器框?
我有以下代码:
#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
(与 object-fit
属性一起用于 'img')。
这将适用于任何大小的容器。
就像这样:
#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>
<picture>
标签,里面有一堆<source>
标签和一个<img>
回退。即使您的图片使用其中一个<source>标签作为其图像来源,它仍将遵守您应用于<img>标签的样式。我正在对<picture>应用object-fit,这就是最初它无法正常工作的原因。希望这可以帮助其他人避免相同的误解。 - Anthony Cregan只需要在你的 img 标签中添加 width: 100%;
,它就会适应容器大小,如果都是正方形则更好。
我花了很长时间才弄明白,因为我试图将 width: 100%
样式添加到图片标签上,而不是直接添加到 'img' 标签上。
你必须同时拉伸图片和图像元素:
#container {
background: steelblue;
width: 333px;
height: 333px;
}
picture, img {
width: 100%;
height: 100%;
}
最简单的方法是添加 width
和 height
到 img
标签中:
img {
width : 100%;
height: 100%;
}
同时使用 object-fit
CSS 属性 来指定元素应如何调整大小以适应其容器。为了保持宽高比:
object-fit: contain;
contain
替换的内容按比例缩放,同时适合元素的内容框。
<source>
元素,使用<picture>
有什么意义? - Michael Lynch