52

I'd like to have an image to have either a height of 725 or a width of 500 and maintain it's aspect ratio. When I have images with a height of over 725 and thinner than 500 they get stretched out to fit a width of 500.

What is the best way to do this?

Below is what I am doing now:

<asp:Image Height="725" width="500" ID="img_DocPreview" />

Update: Changed it to this but have the same problem. If I specify just the height it will maintain the aspect ratio but it exceeds the max width of 500px that i want.

<img style="height:725px;width:500px;" id="img_DocPreview" src="Images/empty.jpg" />
Abe Miessler
  • 82,532
  • 99
  • 305
  • 486

5 Answers5

55

You can try this one

img{
    max-height:500px;
    max-width:500px;
    height:auto;
    width:auto;
}

This keeps the aspect ratio of the image and prevents either the two dimensions exceed 500px

blackgreen
  • 34,072
  • 23
  • 111
  • 129
Daniel Nyamasyo
  • 2,152
  • 1
  • 24
  • 23
38

editied to add support for ie6:

Try

<img style="height:725px;max-width:500px;width: expression(this.width > 500 ? 500: true);" id="img_DocPreview" src="Images/empty.jpg" />

This should set the height to 725px but prevent the width from exceeding 500px. The width expression works around ie6 and is ignored by other browsers.

Nico Burns
  • 16,639
  • 10
  • 40
  • 54
  • Could someone approve if this works? P.S. It wont work in IE6 for sure, because IE6 fails on max-height, max width. Never used it actually, so have forgot if IE7 and 8 isn't running into problems too. – tomsseisums Sep 09 '10 at 16:41
  • 1
    Updated code to use an expression (microsoft proprietary) to add ie6 support. – Nico Burns Sep 09 '10 at 16:55
7

If you only specify either the height or the width, but not both, most browsers will honor the aspect ratio.

Because you are working with an ASP.NET server control, you may consider executing logic on the server side prior to rendering to decide which (height or width) attribute you want to specify; that is, if you want a fixed height under one condition or a fixed width under another.

kbrimington
  • 25,142
  • 5
  • 62
  • 74
  • I actually looked at my code again and there was no reason for me to use the asp.net image control for this, it was actually making more work for me. Should I look at using Javascript to decide if I want my image to use a height or a width? – Abe Miessler Sep 09 '10 at 16:37
  • @Abe - "Should" is a strong word. You certainly could. Perhaps some JQuery masters could chime in with a solution. – kbrimington Sep 09 '10 at 16:49
3

set a style for the image

<asp:Image ID="Image1" runat="server" style="max-height:1000px;max-width:900px;height:auto;width:auto;" />
anandd360
  • 298
  • 3
  • 14
1

You could use some CSS and with the idea of kbrimington it should do the trick.

The CSS could be like this.

img {
  width:  75px;
  height: auto;
}

I got it from here: another post

Community
  • 1
  • 1
Icarin
  • 427
  • 5
  • 7