CSS: Re-size images keeping the aspect ratio in both portrait and landscape.

I recently encountered a problem with resizing images. They had to fit within a containing div but every image on the site I was working on had a mix of portrait and landscape images.

The normal approach would have been to do something like this:

img.landscape {
height: auto;
width: 100%;
}

img.portrait {
height: 100%;
width: auto;
}

This works fine if all your images are one aspect ratio or you can differentiate them from one another by either using classes or some other means.

Now I’m not a CSS guru or a designer by any means so I tried to do what I normally do and googled the problem. I found all sorts of weird solutions people has come up with. Javascript and application based solutions (php) were out of the question and couldn’t find a CSS only solution. So I experimented.

Original example images:
Landscape Image
Portrait Image

This is what was happening:

Landscape Image
Portrait Image

I’ve placed a black border around the containing div elements. As you can see the portrait image is breaking out of it’s containing div. I thought the browser might be smart enough to solve to issue if I just set the width and height to ‘auto’. It didn’t work. So I tried max-height and max-width to 100%. That didn’t work.

In a fit of frustration I tried combined both height, width, max-height and max-width. Lo and behold a miracle occurred.

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

Landscape Image
Portrait Image

This seems to work cross browser as well. I tested this in IE7/8/9, Firefox 8 and Chrome.

Please note I don’t condone the resizing of images using CSS, it’s horrible, I had no choice. Images should always be resized before they reach the browser. If you have to ask why then you shouldn’t be working on websites imo.