Update: It turns out that this is due to a bug in Chrome. I am still looking for workarounds.
I am trying to use lazy loading in Chrome by setting loading="lazy"
on img
elements. I also use the following to let images fit:
img {
max-width: 100%;
height: auto;
}
Unfortunately, the image placeholder that is shown before the image actually loads has a square aspect ratio in Chrome. It does not follow the aspect ratio set in the img
element's width
/height
attributes. This happens under the following conditions:
- Only in Chrome (not in Firefox 75, which, also supports lazy loading).
- Only when setting
loading="lazy"
. Without this attribute, the aspect ratio is preserved.
Is there a solution to preserving the aspect ratio of the image, as set in width
/height
, even with lazy loading?
Here's an article suggesting that what I am doing should work. Please also see the embedded video in the article, saying the same.
You can observe the problem with the below example if throttling the network speed using Chrome's developer tools. I include a screen recording to illustrate the problem. I do not want the image size to change after loading because it causes page elements to shift around.
A minimal example
The HTML:
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur pretium nibh tellus, ac luctus erat viverra sed. Aliquam sed nisi sed sapien tempus consectetur vestibulum vel diam. Ut vel faucibus metus. Donec non sem et purus luctus dictum nec et elit. Suspendisse et ipsum tortor. Proin eros massa, pulvinar a ante eu, imperdiet consequat dolor. Pellentesque sed lacus nulla. Mauris gravida purus sed facilisis sollicitudin.
</p>
<p>
<img src="image.png" width="850" height="422" loading="lazy">
</p>
<p>
Vivamus sagittis faucibus elit non feugiat. Curabitur interdum nulla sed ligula pharetra, in faucibus tortor ullamcorper. Curabitur tristique libero in lobortis posuere. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Quisque quis velit sed tellus aliquet dictum. Fusce vitae consectetur lacus. In scelerisque varius euismod. Nunc scelerisque enim quis lacus dignissim tincidunt. Nulla suscipit, odio eu dictum condimentum, massa elit vestibulum leo, ut lobortis dolor felis vel erat. Cras dapibus, nunc eget sollicitudin semper, elit nisl dictum leo, non semper quam nunc consequat augue. Vivamus bibendum mauris sapien, vel sagittis urna consequat ut.
</p>
</body>
</html>
The CSS:
body {
max-width: 600px;
padding: 20px;
}
img {
border: solid black;
max-width: 100%;
height: auto;
}
The image: