How to proportionally scale images that have dimension attributes

Allowing images to scale along with their container is an important part of responsive web design (and was so even before the term “responsive web design” existed). It’s really quite easy – all you need to do is give the image a width (or max-width) in percent:

img {
    max-width:100%;
}

This will prevent any img element from getting wider than its container. If the container is narrower than the image, the image will scale down. But there is a catch.

If an img element has dimension attributes (width and height) in the markup and you override the width with CSS, the image will remain the height that is specified in the HTML while its width changes. That doesn’t look good.

An easy way to avoid the problem is to simply not specify width and height for images. But specifying what dimensions images have is recommended for performance reasons as it can improve rendering speed in the browser. See Google’s advise in Specifying image dimensions for more. The image size doesn’t have to be in the HTML – it can also be in the CSS. Most of the time I find it more practical and logical to use the HTML attributes.

So you’ll want to specify image dimensions and find another way to make them scale proportionally. Fortunately it’s easy: just add height:auto along with the max-width:

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

This overrides any height attributes in the HTML and lets the image scale properly. See the How to proportionally scale images that have dimension attributes demo page for examples.

Browser notes

Even with something as seemingly simple as this there are a couple of browser differences to be aware of, at least if you’re allowing IE8 and below to get a flexible width layout.

IE7 actually scales the image proportionally whether or not there are any dimension attributes in the markup, even if you do not specify height:auto.

For IE8 to scale images properly, however, you need to give them a width in addition to height:auto. Fortunately width:auto will do the trick without causing problems in the other browsers. So if you need proportional image scaling in IE8, use this:

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

Posted on June 13, 2013 in CSS

Comments are disabled for this post (read why), but if you have spotted an error or have additional info that you think should be in this post, feel free to contact me.