Toadfish
Toadfish

Reputation: 97

CSS: Image to have "Fixed" height, max-width, and maintain aspect ratio?

I have a set of pictures, each with different heights and widths that I want to put into a div tag. I want the picture to try to have a fixed height, unless the width exceeds a fixed amount, whereby I want the height to shrink to maintain the aspect ratio. I tried:

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

This fixes the height but if the image goes beyond 720px width, it squishes the picture horizontally and does not maintain the aspect ratio. Suggestions?

Edit: Maybe a better way of putting this is I'd like the picture to expand to one of those sizes and maintain the aspect ratio.

Upvotes: 9

Views: 59770

Answers (5)

jstaab
jstaab

Reputation: 3865

Wrap the element in a div with the fixed width/height:

<div style="width: 720px; height: 660px;">
  <img src="whatever" />
</div>

Upvotes: 0

joshhunt
joshhunt

Reputation: 5335

Does this meet your needs?

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

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

Edit: Made answer simpler.

Upvotes: 33

Deryck
Deryck

Reputation: 7658

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 re-size the window to see.

Basically, just go get yourself a copy of Normalize.css.

Upvotes: 2

codeaddict
codeaddict

Reputation: 879

If the height is fixed, it wont maintain aspect ratio, Set them both to be the max that you want, and it will maintain the ratio.

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

Edit:

Take a look at your image tags, they might have set width and height on them, If that is the case 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 like that, you won't be able to fix with css.

Upvotes: 1

Nicholas Hazel
Nicholas Hazel

Reputation: 3750

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;
}

Upvotes: 2

Related Questions