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


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


当前回答

我看到很多人都建议对象匹配,这是一个不错的选择。但是,如果您希望它也能在较旧的浏览器中工作,还有另一种方法可以轻松实现。

这很简单。我采用的方法是将图像放置在容器内,然后使用组合将其放置在中心:

position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);

一旦它在中心,我给图像,

// For vertical blocks (i.e., where height is greater than width)
height: 100%;
width: auto;

// For horizontal blocks (i.e., where width is greater than height)
height: auto;
width: 100%;

这使图像获得对象拟合的效果:覆盖。


以下是上述逻辑的演示。

https://jsfiddle.net/furqan_694/s3xLe1gp/

此逻辑适用于所有浏览器。

其他回答

所有提供的答案,包括已接受的答案,都只能在假设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的值必须相同。

下面的代码改编自以前的答案,由我使用名为storm.jpg的图像进行测试。

这是显示图像的简单页面的完整HTML代码。这很完美,我用www.resizemybrowser.com测试过。把CSS代码放在HTML代码的顶部,放在你的头部下面。把图片代码放在你想要的地方。

<html>
    <head>
        <style type="text/css">
            #myDiv
            {
                  height: auto;
                  width: auto;
            }
            #myDiv img
            {
                max-width: 100%;
                max-height: 100%;
                margin: auto;
                display: block;
            }
        </style>
    </head>

    <body>
        <div id="myDiv">
            <img src="images/storm.jpg">
        </div>
    </body>
</html>

查看我的解决方案: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;
}

我看到很多人都建议对象匹配,这是一个不错的选择。但是,如果您希望它也能在较旧的浏览器中工作,还有另一种方法可以轻松实现。

这很简单。我采用的方法是将图像放置在容器内,然后使用组合将其放置在中心:

position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);

一旦它在中心,我给图像,

// For vertical blocks (i.e., where height is greater than width)
height: 100%;
width: auto;

// For horizontal blocks (i.e., where width is greater than height)
height: auto;
width: 100%;

这使图像获得对象拟合的效果:覆盖。


以下是上述逻辑的演示。

https://jsfiddle.net/furqan_694/s3xLe1gp/

此逻辑适用于所有浏览器。

如果您使用Bootstrap,只需将img响应类添加到img标记:

<img class="img-responsive" src="img_chania.jpg" alt="Chania">

引导映像