Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I need "height: auto" for responsive images?

Tags:

css

Is it necessary to define the height: auto now days? and what the reasons is?

img {
    max-width: 100%;
    height: auto;
}

Thanks.

like image 736
Stickers Avatar asked Oct 22 '25 03:10

Stickers


2 Answers

On an image without a height dimension explicitly set anywhere, it will actually default to height auto. So if you set max-width: 100%; the height will automatically be calculated by the browser to be the correct aspect ratio.

You may then think that it is not necessary to set the height to auto in the css but the real reason for it is if a height has been set on the img element with the height html attribute like this:

<img src="#" height="500" />

Although you may not set the height attribute explicitly yourself I know that wordpress for instance does set the height attribute on images that are pulled from the media library.

In this case if you only have set max-width to 100% the image will not be wider than the containing element but the aspect ratio will be wrong, the image most likely will be stretched taller. Use the css height auto to override the img tag height attribute.

That is why Bootstraps .img-responsive class sets height: auto;.

like image 171
Larry Lawless Avatar answered Oct 23 '25 18:10

Larry Lawless


No, it's not.

MDN's docs on height states:

Initial value: auto

So, height property will be auto by default.

like image 20
LcSalazar Avatar answered Oct 23 '25 20:10

LcSalazar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!