Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preserve image aspect ratio with the height fixed

Tags:

html

css

I am working with some icons in a table and I am looking to keep the aspect ratio of the icons.

The heights all have to be the same (18px) but the width can vary.

I have seen other solutions for these when the width is fixed and height is set to auto like below this solution

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

Some sample code is below for my table (at least just one cell in the table)

<td class="set_symbol" style="text-align: center;">
  <img src="/static/img/symbols_large/Gatecrash_Uncommon.gif" style="height: 18px;">
</td>

What I would like to do is to keep the height of the image at 18px and have the width be whatever fits the aspect ratio.

Also, I have no qualms about browsers. So if it takes CSS3 or whatever, doesn't matter.

like image 608
Milo Gertjejansen Avatar asked Jul 10 '13 02:07

Milo Gertjejansen


People also ask

What does it mean to maintain the aspect ratio of an image?

Maintaining aspect ratio describes taking steps to ensure that the width and height of an image remain proportionally the same as you edit an image. You could be, for example, resizing an image to make it smaller, or cropping into it in post-production.

Does object fit preserve aspect ratio?

The entire object is made to fill the box, while preserving its aspect ratio, so the object will be "letterboxed" if its aspect ratio does not match the aspect ratio of the box.

Why is it important to maintain the aspect ratio of an image when it is resized?

When scaling your image, it's crucial to maintain the ratio of width to height, known as aspect ratio, so it doesn't end up stretched or warped. If you need a specific width and height, you may need a mixture of resizing and cropping to get the desired result.


1 Answers

What I would like to do is to keep the height of the image at 18px and have the width be whatever fits the aspect ratio.

This does what you want:

img { 
    height: 18px;
}

See demo here.

sample image

Keep in mind, max-heigth can be used instead of height if you want to keep small images small.

like image 191
acdcjunior Avatar answered Nov 02 '22 18:11

acdcjunior