I have some straightforward constraints for my img tags.
- They should not render larger certain maximum dimensions regardless of their intrinsic size.
- They should not render smaller than their minimum dimensions.
- They should respect their aspect ratio if at all possible given the maximum and minimum dimensions.
- An image that cannot respect both the size constraints AND the aspect ratio will be cropped using
object-fit
.
- An image that cannot respect both the size constraints AND the aspect ratio will be cropped using
Because I know the sizes of my images before they load, I can set their dimensions on the elements directly.
If I do the following, the images have consistent dimensions during all states (loading, loaded, error).
<img src="foo" width="30" height="80" />
img {
display: block;
background: gray;
max-height: 60px;
max-width: 100px;
object-fit: cover;
}
The problem is that the images are cropped at the max-height
even though they could satisfy all their constraints by scaling down. In this case, the resulting image has dimensions 30×60 even though it’s intrinsic size is 30×80.
Setting the width
and height
to auto
causes the images to respect their aspect ratio, but doing so also causes the images to ignore their intrinsic dimensions while loading. (Strangely, they do not ignore their dimensions in their error state.) Firefox does not have this problem.
Here’s the updated CSS.
img {
display: block;
background: gray;
width: auto;
height: auto;
max-height: 60px;
max-width: 100px;
object-fit: cover;
}
Is there a bulletproof way to get Chrome to respect all these constraints even while loading? I’m worried the answer is “no”.
I made a codepen for reference. Clicking the “refresh” button will trigger the layout shift. https://codepen.io/malectro/pen/dyBRMrE