"Height: auto;" required when adjusting image width?
When setting the width to <img> , either using width or max-width , I saw that many developers and some frameworks (like bootstrap) also set height: auto .
In such cases, height: auto is required, and if so, why? (Assuming you want to preserve the image proportionally when resized and that height has not been previously set in CSS.)
Someone said that it is necessary for IE10 on Windows Phone 8. (Which seems strange to me.) Could it be that some browsers require this option?
Example ( fiddle ):
div{ border: 2px solid red; width: 300px; } .maxwidth{ max-width: 100%; } .width{ width: 100%; } <p><code>max-width: 100%</code>:</p> <div><img class="maxwidth" src="https://placeimg.com/640/480/animals"></div> <p><code>width: 100%</code>:</p> <div><img class="width" src="https://placeimg.com/640/480/animals"></div> <p>No <code>height: auto</code> is used, but images still stay proportional.</p> For starters, the initial value for height is auto , so if it has not been redefined elsewhere, you will not need to specify height: auto .
Also, I don't know how much this applies to the img element itself in CSS images (backgrounds, etc.), but I believe that the browser should handle this automatically anyway. If this documentation also applies to the img element, I believe that the section Default sizing algorithm for CSS Image Values ββand Level 3 of the hosted content explains how the browser should handle this:
The default sizing algorithm is defined as follows:
If the specified size has a specific width and height, the size of a particular object is determined by the width and height.
If the specified size is only the width or height (but not for both), then the specific size of the object is specified with the specified width or height. Another dimension is calculated as follows:
If the object has an internal aspect ratio, the missing size of the specific size of the object is calculated using the internal aspect ratio and the present dimension.
Otherwise, if the missing dimension is present in the internal dimensions of the object, the missing size is taken from the internal values ββof the object.
Otherwise, the missing size of a specific object size is taken from the default object size.
Update
Bootstrap seems to use it to override any custom height attribute present in the img element to ensure that height always calculated from width .
height: auto is defined only through the .img-responsive class. It is defined so that it overrides the image height attribute (if one is set).
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet"/> <h2>Without auto height</h2> <img src="http://www.placehold.it/200" class="" width="200" height="100"> <h2>With auto height</h2> <img src="http://www.placehold.it/200" class="img-responsive" width="200" height="100">