Automatically size the images according to their format

I am working with images that are in both landscape and portrait format in a website. I know how to size and display them with CSS by using classes like imgh and imgv. What I am wondering is if there is someway to automatically size the images according to their format without having to assign a respective class to them? That is, have an image fill its containing DIV but retain its format. I’ve tried max-width and max-height. It works for landscape format images but not for portrait format.


It works better to make the line-height the same as the DIV height and add vertical-align:middle; to .box img

Now, if only I can get :hover to work. Because the two formats (portrait and landscape) are relatively positioned in different places inside the containing DIV, one or the other is too far or not far enough left when hovered over.

Try setting the image using a width percentage and max-width but not a height:

 <img src='whatever.jpg' style='width:98&#37;; max-width:888px; margin:auto;' alt='whatever' />

The image should align itself to the containing element and also be centered.


I forgot to include the text-align:center. I use a tac class instead.

I used similar code frequently on my sites and shrink the image to fit inside an expanding div. The max-width: pixels was set to the maximum width of the image otherwise small images would expand (with distortion) to the width of the containing div.

Your max-width: percentage is a better solution and can even be increased to 100%. I will start using your suggestion on my sites.

You may also try:

  width:300px; height:300px;
  text-align:center; margin:auto

The line-height: can be adjusted to vertically center the image.


Thanks John, but that doesn’t work.

However, this does:

.box img{max-width:98%;max-height:98%;margin:auto;}
<div class="box">
<img src="image.jpg" />

For both Coldfusion and PHP you can find different resize scripts if that’s where ou are looking for