Proportional Image Scaling in CSS

While you should always use the appropriately-sized images on websites (rather than serving 10-megapixel images on your pages — people actually do that!), when dealing with dynamic content, sometimes it’s nice to ensure that images don’t expand beyond their container.

That’s easily solved with setting a max-width value in the CSS on my other blog, but the problem was that this seemed to only adjust the width. I wanted to scale images proportionally, so if an image that was too big made it through, it wouldn’t look awful.

It turned out to have a really easy fix — but it was astonishingly hard to find information on. Here’s the fix:


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

The “height: auto” is the key, making height proporational when it is resized. (The “100%” in max-width gets interpreted as 100% of the element it’s contained in, not 100% of the image itself.)

One thought on “Proportional Image Scaling in CSS

Leave a Reply

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

To create code blocks or other preformatted text, indent by four spaces:

    This will be displayed in a monospaced font. The first four 
    spaces will be stripped off, but all other whitespace
    will be preserved.
    
    Markdown is turned off in code blocks:
     [This is not a link](http://example.com)

To create not a block, but an inline code span, use backticks:

Here is some inline `code`.

For more help see http://daringfireball.net/projects/markdown/syntax

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>