CSS image scaling to fit within area not distort

RIK picture RIK · Mar 20, 2011 · Viewed 97.3k times · Source

Is there a way with CSS or otherwise of making an image fit within an area. Lets say I have multiple images of different sizes and I want them all to fit within a div of 150px by 100px. I don't want to scale the images though as some may be tall and others narrow I simply want them to fit within this area with the rest hidden.

I thought about using overflow:hidden but it appears to not be hidden in IE6.

Any ideas?

Answer

Sang Suantak picture Sang Suantak · Mar 20, 2011

You should try using this:

img{
  width: auto;
  max-width: 150px;
  height: auto;
  max-height: 100px;
}

Edit: Looks like IE6 doesn't support max-width and max-height properties. However, you can implement the workaround given here: max-width, max-height for IE6

Excerpt (in case linked article stops working):

img {
  max-height: 100px;
  max-width: 100px;
  width: expression(document.body.clientWidth > 150? “150px”: “auto”);
  height: expression(document.body.clientHeight > 100? “100px”: “auto”);
}