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

问题描述 投票:2回答:4

我有以下代码:

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

如何让图片填满容器盒?

Here's a codepen

html css
4个回答
4
投票

你必须在'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>

0
投票

你必须拉伸BOTH图片和img元素:

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

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

0
投票

只需添加一个width: 100%;到你的img。如果两者都是正方形,它将适合容器。


0
投票

最简单的方法是将widthheight添加到img

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

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

object-fit: contain;

根据MDN documentation

包含

替换的内容被缩放以在适合元素的内容框时保持其纵横比。

© www.soinside.com 2019 - 2024. All rights reserved.