Scaling Images Proportionally in CSS with Max-width

Solution 1:

Contrary to the accepted answer, you can do this without specifying the size in the HTML. It can all be done in CSS:

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

Solution 2:

You need to specify the original width and height:

<img src="/whatever" width="100" height="200" alt="Whatever" />

And then use something like this in the CSS:

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

You could try this with jQuery if you don't have the width and height up front, but your mileage may vary:

$(function(){
    $('#content img').load(function(){
       var $img = $(this);
       $img.attr('width', $img.width()).attr('height', $img.height());
    });
});

Obviously replace #content with whatever selector you want to scope the functionality to.

Solution 3:

when setting up constant width use:

height: auto

Solution 4:

Here's how to do it with no Javascript. Set your max-width to the length you want.

#content img { 
   max-width: 620px;
   height: auto;
}

This worked for me tested on a Mac with Firefox 28, Chrome 34 and Safari 7 when I had no width or height settings explicitly set in the img tags.

Don't set your width in CSS to 100% after the max-width setting as one person suggested because then any images that are narrower than the width of the container (like icons) will be blown up much larger than desired.