简体   繁体   中英

Resize an image to stay within the viewport

How can I make an image resize and maintain aspect ratio to stay within the container if the image is larger than the container, but not resize if the image is smaller than the container.

If the width of the image is larger than the width of the container then the following code should apply.

img {
    width: 100%;
    height: auto;
}

If the width of the image is smaller than the width of the container then the following code should apply.

img {
    width: auto;
    height: 100%;
}

I tried using the following code, but some strange things happen when the image width is larger then the container's width.

img_w = parseInt($("#img").css("width"));
screen_w = parseInt($(window).width());

img_w = parseInt($("#img").css("width"));
screen_w = parseInt($(window).width());

if (img_w > screen_w) {
    $("#img").css("width", screen_w + "px"); // like 100%;
    $("#img").css("height", "auto");
} else {
    $("#img").css("width", "auto");
    $("#img").css("height", "100%");
}

Problem solved with the following CSS:

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

I tried your code and you can see here the result: http://jsfiddle.net/g6rL3L5h/ I think it's now ok and working.

I just delete 'html' in your css.

body {
    width: 100%;
    height: 100%;
    margin: 0;
    padding: 0;
    text-align: center;
  }

do you needed this?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM