Why width and height attributes of an image tag is automatically set to the natural size of the image, only in IE10 and below.
TL;DR : In IE10 and below, if an image tag is dynamically inserted to the DOM, the width and height attributes of the image tag are set to the natural sizes
I want to share my experience in solving the problem that an image was not displayed correctly because the width and height attributes of the image were automatically set in IE10 and below.
Let’s open the below html file in browsers IE10 and Chrome.
* Result of IE11 and Chrome
<img src="https://cdn.011st.com/11dims/resize/128x128/quality/75/11src/browsing/banner/2019/11/21/12937/2019112115432102791_0_1.png">* Result of IE10 and below
<img src="https://cdn.011st.com/11dims/resize/128x128/quality/75/11src/browsing/banner/2019/11/21/12937/2019112115432102791_0_1.png" width="128" height="128">
Surprisingly, the width and height attributes were set automatically in IE10.
In browsers below IE10, if an image tag is dynamically inserted to the DOM, the attributes was automatically set to the natural size(128x128). This feature can occur an issue where the shape of the image is broken. Suppose the following CSS is included.
img.target {
width: 64px;
}
In IE11 or higher browsers, the height style is also set to 64px according to the ratio of the image, so it will be correctly exposed as 64x64. This is because the height style have default value ‘auto’.
However, in browsers below IE10, due to the above feature, the attribute style is set to the style of image. So, the image is exposed in 64x128 size with broken ratio.
img[Attribute Style] {
width: 128px;
height: 128px;
}
Therefore, in this case, you should set ‘auto’ on height style in CSS.
img.target {
width: 64px;
height: auto;
}
You can avoid this issue by always setting both the width and height styles of the image tag. For more information, see Why should both the width and height styles of the image tag be set?