How can I resize an image dynamically with CSS as the browser width/height changes?

depi picture depi · Jan 13, 2011 · Viewed 405.6k times · Source

I wonder how I could make an image resize along with the browser window, here is what I have done so far (or download the whole site in a ZIP).

This works okay in Firefox, but it has problems in Chrome: the image does not always resize, it somehow depends on the size of the window when the page was loaded.

This also works okay in Safari, but sometimes the image is loaded with its minimum width/height. Maybe this is caused by the image size, I am not sure. (If it loads okay, try to refresh several times to see the bug.)

Any ideas on how could I make this more bulletproof? (If JavaScript will be needed I can live with that, too, but CSS is preferable.)

Answer

Kurt Schindler picture Kurt Schindler · Feb 25, 2012

This can be done with pure CSS and does not even require media queries.

To make the images flexible, simply add max-width:100% and height:auto. Image max-width:100% and height:auto works in IE7, but not in IE8 (yes, another weird IE bug). To fix this, you need to add width:auto\9 for IE8.

source: http://webdesignerwall.com/tutorials/responsive-design-with-css3-media-queries

CSS:

img {
    max-width: 100%;
    height: auto;
    width: auto\9; /* ie8 */
}

And if you want to enforce a fixed max width of the image, just place it inside a container, for example:

<div style="max-width:500px;">
    <img src="..." />
</div>

JSFiddle example here. No JavaScript required. Works in latest versions of Chrome, Firefox and IE (which is all I've tested).