Sizing Images Responsively

Published January 31, 2014 by CSS Newbies.

Images are sort of a special beast in the HTML animal kingdom. They’re technically inline elements, but they don’t really behave like them. For example, inline elements can’t have widths and heights applied. And yet, you and I both know that images have widths and heights.

This can cause trouble in responsive web designs. While inline elements automatically play nicely in RWD, resizing to fill their container, images do not. They’ll bust right out of that shiz and wreak all sorts of havoc, turning your nice narrow sidebar into something like this:

See the Pen Sizing Images Responsively 1 by Rob Glazebrook (@rglazebrook) on CodePen.

That is likely not what you intended. Happily, the fix is simple, safe, and effective.

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

That’s all it takes to make our images behave:

See the Pen Sizing Images Responsively 2 by Rob Glazebrook (@rglazebrook) on CodePen.

Here, max-width: 100% is ensuring that we never escape the bounds of our container, while height:auto resizes the height to proportionally match whatever width max-width gives us.

The width: auto bit may seem unnecessary, and for modern browsers, it is. It’s there as a fix for IE8 and below (go figure). Without it, IE can stretch your images. The problem comes in when an image has width and height attributes set, like this:


A lot of CMSs do that by default, to ensure the proper space is left for the image when the document is rendered before the image has downloaded. It seems that, without the width: auto bit, IE will resize the width, but leave the height as it was specified in the height attribute, causing your images to look like this:

An image being stretched horizontally by Internet Explorer 8.

Not. What. We. Wanted.

So to prevent that, keep that width: auto in there. It feels redundant to me, but it’s better than the alternative.

6 Responses

  1. Pingback: Embedding Video in a Responsive Site | Lunarium Design

  2. Pingback: Simple Table Column Highlighting | Lunarium Design

  3. Pingback: Embedding Video in a Responsive Site - Orlando Web Design - Orlando Web DesignOrlando Web Design

  4. Pingback: Using Box-sizing border-box CSS | Lunarium Design

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>