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

会有一股神秘感。 提交于 2019-12-23 07:54:37

问题


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.


回答1:


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.




回答2:


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!



来源:https://stackoverflow.com/questions/8050056/scale-down-but-not-up-images-using-css-to-fit-div-container-in-ie9-max-width

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!