Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scale down (but not up) images using CSS to fit div container in IE9 (max-width: 100% fix)

I cannot use JS, this should be archived by CSS only. Container (DIV) is auto width (flexible) "table-cell" element.

I'd want to scale image down only when it width is larger than container (user can resize window - that's the reason).

I've used code shown below but it work only on IE7.

max-width: 100%;
height: auto;
width: auto\9;

I've tried to find any working fix for IE9, but without success.

like image 409
Simek Avatar asked Nov 08 '11 12:11

Simek


2 Answers

Your max-width needs to be set to the image size and then width to 100% like so:

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

Of course, this means that your max-width must be dynamically set based off the image being loaded, which may not be practical.

like image 125
ScottS Avatar answered Sep 30 '22 18:09

ScottS


I stumbled upon this old question while trying to do the exact same thing the OP was trying. I am answering for anyone who may land here. Upon examining http://jsfiddle.net/SAada/2/ mentioned by the OP, I found an interesting solution:

setting

height: auto;

will ensure that the image will not be stretched / scaled up. At the same time, setting

max-width: 100%

will ensure that if the parent element width is less than the image width, the image is scaled down.

Thus, the combination that works for me is:

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

Oh, and after some more search, I discovered that this technique is also used by Bootstrap for responsive images!

like image 39
Jignesh Smart Avatar answered Sep 30 '22 17:09

Jignesh Smart