Resize the image so that it remains in the viewport.

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

If the width of the image is greater than the width of the container, then the following code should be applied.

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

If the width of the image is less than the width of the container, then the following code should be applied.

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

I tried using the following code, but some strange things happen when the width of the image is larger than the width of the container.

 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%"); } 
+5
source share
2 answers

The issue was resolved using the following CSS:

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

I tried your code, and you can see the result here: http://jsfiddle.net/g6rL3L5h/ I think now everything is fine and working.

I just delete the 'html' in your css.

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

You need it?

-1
source

All Articles