Proportional image scaling in your responsive web design

Having images scale properly along with its container is a given when it comes to responsive web design. I’ve seen a few responsive web site over the last few weeks who seems to have forgotten this, which is a real shame since it is so very easy to fix this. All you need to do is give the images a percentage based max-width.

img {
  max-width: 100%;
}

This will keep the image elements nicely confined within their container.

But there’s a catch, right?

Sure enough, there’s a catch. Many content management systems, like for instance WordPress, add dimension attributes to all images (as well as whole heap of classes, superfluous alt attribute content etc, but that’s is another story). This is actually a good thing, since adding dimension attributes prevents content reflow when a page is loading. The problem is that images with the max-width set to 100% will loose its aspect ratio and risk looking squashed. To fix this, all we need to do is to add height: auto; to the stylesheet.

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

Any height attribute set in the image element will be overridden by this and prevent disproportionate aspect ratios.

Browser caveat emptor

As always, legacy Internet Explorer needs a little extra attention for this to work. For the proportional scaling to work properly in at least Internet Explorer 8, you need to add a width: auto;.

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

That’s it! You should now have images that scales nicely with your content.

Close Menu