如何自动调整大图像的大小,使其适合较小宽度的div容器,同时保持其宽高比?


示例:stackoverflow.com-当图像插入到编辑器面板上,并且图像太大而无法放到页面上时,图像将自动调整大小。


当前回答

将图像所需的高度和宽度提供给包含<img>标记的div。不要忘记在正确的样式标记中给出高度/宽度。

在<img>标记中,将最大高度和最大宽度设置为100%。

<div style="height:750px; width:700px;">
    <img alt="That Image" style="max-height:100%; max-width:100%;" src="">
</div>

正确后,可以在适当的类中添加详细信息。

其他回答

查看我的解决方案:http://codepen.io/petethepig/pen/dvFsA

它是用纯CSS编写的,没有任何JavaScript代码。它可以处理任何大小和方向的图像。

给定这样的HTML:

<div class="image">
  <div class="trick"></div>
  <img src="http://placekitten.com/415/200"/>
</div>

CSS代码将是:

.image {
  font-size: 0;
  text-align: center;
  width: 200px;  /* Container's dimensions */
  height: 150px;
}
img {
  display: inline-block;
  vertical-align: middle;
  max-height: 100%;
  max-width: 100%;
}
.trick {
  display: inline-block;
  vertical-align: middle;
  height: 150px;
}

正如这里所回答的,你也可以使用vh单位而不是最大高度:如果它在你的浏览器(如Chrome)上不起作用,100%:

img {
    max-height: 75vh;
}

所有提供的答案,包括已接受的答案,都只能在假设div包装器大小固定的情况下工作。因此,无论div包装器的大小如何,这都是如何实现的,如果您开发响应页面,这非常有用:

在DIV选择器中编写以下声明:

width: 8.33% /* Or whatever percentage you want your div to take */
max-height: anyValueYouWant /* (In px or %) */

然后将这些声明放入IMG选择器中:

width: "100%" /* Obligatory */
max-height: anyValueYouWant /* (In px or %) */

非常重要:

对于DIV和IMG选择器,maxHeight的值必须相同。

当图像太小时,Thorn007的公认答案不起作用。

为了解决这个问题,我添加了一个比例因子。这样,它会使图像变大,并填充div容器。

例子:

<div style="width:400px; height:200px;">
  <img src="pix.jpg" style="max-width:100px; height:50px; transform:scale(4); transform-origin:left top;" />
</div>

笔记:

对于WebKit,必须添加-WebKit transform:scale(4)-webkit转换原点:左上;在风格上。比例因子为4时,最大宽度=400/4=100,最大高度=200/4=50另一种解决方案是将最大宽度和最大高度设置为25%。这更简单。

以下内容非常适合我:

img{
   height: 99999px;
   object-fit:contain;
   max-height: 100%;
   max-width: 100%;    
   display: block;
   margin: auto auto;
}