How to maintain aspect ratio using HTML IMG tag

sunil kumar picture sunil kumar · Oct 16, 2012 · Viewed 224.7k times · Source

I am using an img tag of HTML to show a photo in our application. I have set both its height and width attribute to 64. I need to show any image resolution (e.g. 256x256, 1024x768, 500x400, 205x246, etc.) as 64x64. But by setting the height and width attributes of an img tag to 64, it's not maintaining the aspect ratio, so the image looks distorted.

For your reference my exact code is:

<img src="Runtime Path to photo" border="1" height="64" width="64">

Answer

Turnip picture Turnip · Oct 16, 2012

Don't set height AND width. Use one or the other and the correct aspect ratio will be maintained.

.widthSet {
    max-width: 64px;
}

.heightSet {
    max-height: 64px;
}
<img src="http://placehold.it/200x250" />

<img src="http://placehold.it/200x250" width="64" />

<img src="http://placehold.it/200x250" height="64" />

<img src="http://placehold.it/200x250" class="widthSet" />

<img src="http://placehold.it/200x250" class="heightSet" />