具有固定宽度和自动调整高度的css图像



我有一个固定的div,css宽度:400px;高度:280px;但我的图像来自不同的维度,有些是肖像一些风景。无论源大小如何,我如何将图像适合/拉伸/填充到div 大小?

@giorgi-parunov 有最简单和最好的方法。 如果你想使用 ,我建议你使用 css 使图像响应div。

img {
     max-width:100%;
     height: auto
}

您也可以使用object-fit: cover

如果你对div有固定的大小,你可以将 img 的height/width设置为 100%。

div {
  width: 150px;
  height: 50px;
  border: 1px solid black;
}
img {
  width: 100%;
  height: 100%;
}
<div>
  <img src="http://cdn2.spectator.co.uk/files/2016/04/iStock_000069830477_Small.jpg">
</div>

如果要填充div但又想保持图像纵横比,则可以使用类似于使用 img 作为背景时background-size: cover object-fit: cover

div {
  width: 100px;
  height: 150px;
  border: 1px solid black;
}
img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
<div>
  <img src="http://cdn2.spectator.co.uk/files/2016/04/iStock_000069830477_Small.jpg">
</div>

我认为最好的方法是,使用背景图像。

网页<div style="background-image: url("paper.gif"); background-size: cover; background-position: center;"></div>

这是在没有Javascript的情况下将图像添加到div的最佳方法。

您可以查看此答案以适合以容器为中心的任何图像https://stackoverflow.com/a/36063374/2894798在您的情况下,代码将是

 .container {
  display: flex;
  justify-content: center;
  align-items: center;
  border: 1px solid;
  width: 400px; /*customize to your needs 100%*/
  height: 280px; /*customize to your needs*/
}
.container img
{
 max-width:100%;
 max-height:100%;
}

这是小提琴

最新更新