Warm tip: This article is reproduced from serverfault.com, please click

html-如何自动调整图像大小以适合“div”容器?

(html - How do I auto-resize an image to fit a 'div' container?)

发布于 2010-06-12 17:00:37

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


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

Questioner
001
Viewed
0
Kevin 2018-05-15 06:18:33

不要对图像标签应用明确的宽度或高度。相反,给它:

max-width:100%;
max-height:100%;

此外,height: auto;如果你只想指定宽度。

示例:http : //jsfiddle.net/xwrvxser/1/

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

.portrait {
    height: 80px;
    width: 30px;
}

.landscape {
    height: 30px;
    width: 80px;
}

.square {
    height: 75px;
    width: 75px;
}
Portrait Div
<div class="portrait">
    <img src="http://i.stack.imgur.com/xkF9Q.jpg">
</div>

Landscape Div
<div class="landscape">
    <img src="http://i.stack.imgur.com/xkF9Q.jpg">
</div>

Square Div
<div class="square">
    <img src="http://i.stack.imgur.com/xkF9Q.jpg">
</div>