resize an image to fit a div container

How do you auto-resize a large image so that it will fit into a smaller width div container whilst maintaining it's 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.


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>

https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit

turns out there's another way to do this.

<img style='height: 100%; width: 100%; object-fit: contain'/> 

will do the work. It's CSS3 stuff.

Fiddle: http://jsfiddle.net/mbHB4/7364/


Currently there is no way to do this correctly in a deterministic way, with fixed-size images such as JPEGs or PNG files.

To resize an image proportionally, you have to set either the height or width to "100%", but not both. If you set both to "100%", your image will be stretched.

Choosing whether to do height or width depends on your image and container dimensions:

  • If your image and container are both "portrait shaped" or both "landscape shaped" (taller than they are wide, or wider than they are tall, respectively), then it doesn't matter which of height or width are "%100".
  • If your image is portrait, and your container is landscape, you must set height="100%" on the image.
  • If your image is landscape, and your container is portrait, you must set width="100%" on the image.
  • If your image is an SVG, which is a variable-sized vector image format, you can have the expansion to fit the container happen automatically.

    You just have to ensure that the SVG file has none of these properties set in the <svg> tag:

    height
    width
    viewbox
    

    Most vector drawing programs out there will set these properties when exporting an SVG file, so you will have to manually edit your file every time you export, or write a script to do it.

    链接地址: http://www.djcxy.com/p/41388.html

    上一篇: 如何扩展可拖动的jQuery可拖动区域

    下一篇: 调整图像大小以适应div容器