CSS: Does the image have a fixed height, maximum width and maintains aspect ratio?

I have a set of images, each with different heights and widths, which I want to put in a div tag. I want the image to try to set a fixed height if the width does not exceed a fixed value, so I want the height to decrease to maintain aspect ratio. I tried:

 .ArtistPic { height: 660px; max-width: 720px; } 

This captures the height, but if the image goes beyond the width of 720 pixels, it compresses the image horizontally and does not support aspect ratio. Suggestions?

Edit: Perhaps the best way to do this is, I would like the image to expand to one of these sizes and maintain the aspect ratio.

+6
source share
4 answers

Does this fit your needs?

 .ArtistPic { max-width: 720px; max-height: 660px; } 

See http://jsfiddle.net/7s9wnjse/1/ .

Edit: simplified answer.

+27
source

Use background-size:cover;

Fiddle: http://jsfiddle.net/SinisterSystems/cukgh/3/

 .box { float:left; margin:15px; width:100px; height:100px; background:url("http://www.hdwallpapers3g.com/wp-content/uploads/2014/01/Images-6.jpg"); background-size:cover; } 
+2
source

This will give you what you want:

CSS

 img { width: auto; /* set to anything and aspect ratio is maintained - also corrects glitch in Internet Explorer */ height: auto; /* set to anything and aspect ratio is maintained */ max-width: 100%; border: 0; /* for older IE browsers that draw borders around images */ } 

View here and resize the window to see.

Basically, just make yourself a copy of Normalize.css .

+2
source

If the height is fixed, it will not maintain the aspect ratio, set them to the maximum you want, and it will maintain the aspect ratio.

 .ArtistPic { max-width: 720px; max-height:660px; } 

Edit:

Take a look at your image tags, they can set the width and height on them. If so, you will need to remove them.

 <img src="image/path" width="250px" height="3005px" alt="valid image"/> 

If it has width and height on it, you cannot fix it with css.

0
source

All Articles