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

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

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

How do you auto-resize a large image so that it will fit into a smaller width div container whilst maintaining its width:height ratio?


Example: stackoverflow.com - when an image is inserted onto the editor panel and the image is too large to fit onto the page, the image is automatically resized.

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

Do not apply an explicit width or height to the image tag. Instead, give it:

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

Also, height: auto; if you want to specify a width only.

Example: 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>