I am seeking a method to reserve space in my layout for images before they are loaded by adding width
and height
properties to the img
element.
This approach functions as anticipated:
img {
display: block;
border: 1px solid tomato;
}
<img src="" width="300" height="400" alt="">
However, when I attempt to limit the image size using max-width
in my CSS, setting height: auto
results in the collapse of the image's height:
img {
display: block;
border: 1px solid tomato;
max-width: 200px;
height: auto;
}
<img src="" width="300" height="400" alt="">
Is there a way to compel browsers to maintain the aspect ratio based on HTML attributes?
The issue persists. Both Firefox and Chrome now support internal mapping of width and height to aspect ratio, which fulfills my requirements.
One observation I have made is that the src
attribute must be set for this functionality to work. Setting an image as fully loaded appears to reset the aspect ratio settings.
To accommodate lazy loading, a placeholder image can be used with the correct aspect ratio assigned to the src
attribute.
Despite working well in Chrome and Firefox, I am still looking for a solution that also caters to older browsers and Safari (excluding IE).