使图片元素中的图像适应其容器

11

我有以下代码:

#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>

如何使图片填充容器框?

这里是一个CodePen示例


Mike已经回答了,我只想补充一下,“object-fit”不支持IE,也不完全支持Edge,以防这对你的使用很重要 ;) https://caniuse.com/#search=object-fit - Marcel Schmid
不使用<source>元素,使用<picture>有什么意义? - Michael Lynch
5个回答

30

您需要在“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>


这对我有效,但想知道为什么有效? - cuka
我所需要的只是img宽度为100%。在图片标签上设置这些属性对我没有任何作用。 - carlin.scott
1
值得指出的是,有一件事情困扰了我。我有一个<picture>标签,里面有一堆<source>标签和一个<img>回退。即使您的图片使用其中一个<source>标签作为其图像来源,它仍将遵守您应用于<img>标签的样式。我正在对<picture>应用object-fit,这就是最初它无法正常工作的原因。希望这可以帮助其他人避免相同的误解。 - Anthony Cregan

2

只需要在你的 img 标签中添加 width: 100%;,它就会适应容器大小,如果都是正方形则更好。


0

我花了很长时间才弄明白,因为我试图将 width: 100% 样式添加到图片标签上,而不是直接添加到 'img' 标签上。


0

你必须同时拉伸图片和图像元素:

#container {
  background: steelblue;
  width: 333px;
  height: 333px;
}

picture, img {
  width: 100%;
  height: 100%;
}

0

最简单的方法是添加 widthheightimg 标签中:

img {
  width : 100%;
  height: 100%;
}

同时使用 object-fit CSS 属性 来指定元素应如何调整大小以适应其容器。为了保持宽高比:

object-fit: contain;

根据MDN文档

contain

替换的内容按比例缩放,同时适合元素的内容框。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接