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

2

9

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.

Honea answered 8/11, 2011 at 12:2 Comment(3)
adding just max-width: 100%; to the img tag doesn't work? test it here resizing the window. It works for IE7, IE8, Chrome and Firefox, but I can test it in IE9 right now. Anyway, how is IE9 behaving?Bistoury
This is the exact situation and problem which I had to solve: jsfiddle.net/SAada/2Honea
The style settings you're using fro the image are fine. Check this sample that works for popular browsers incl IE9 - jsfiddle.net/cTxYc The settings you've specified for the div's are medddling with the settings for the imageSkeie
H
6

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.

Hanshaw answered 8/11, 2011 at 13:53 Comment(4)
What if I don't know the image size? User can post it without any limitation and it should scale down flexible.Honea
Then you cannot limit it to a max-width, because you won't know the max-width that you will allow (unless you are going to just allow a max for all images, regardless.Hanshaw
So how the mentioned in original question code works for IE7?Honea
This is a guess (based off memory). I believe IE7 actually does not support max-width unless you are running a strict doctype. So it may be interpreting max-width as width. In IE7 can you make your image grow larger than the image size itself? If so, that is probably what is happening. If that is not the answer, I do not know.Hanshaw
T
5

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!

Truditrudie answered 28/12, 2017 at 12:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.