How to handle images with unknown dimension for CLS

Viewed 189

To improve the CLS (Cumulative Layout Shift) you are supposed to set the width and height attribute of images. Is there any other proper way to handle images, if it's dimension is unknown?

On my website there is a section were brand logos are displayed. The logo can be different on every page and there is no way to get the size of the image in the backend and set the attributes accordingly.

Is there any other way to handle that properly? The image should not be stretched.

That's the current code:

img {
  max-height: 100px;
  max-width: 150px;
}
<a>
  <img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSgWHIrKgS3d0VR8LASdW4cXFkM5rkWtFDNgw&usqp=CAU" alt="someLogo">
</a>

EDIT:

I now came up with this solution (don't know if it's best practice, but at least google PageSpeed Insights is not complaining anymore):

a {
  display: block;
  height: 100px;
  width: 150px;
  position: relative
}

img {
  position: absolute;
  top: 0;
  bottom: auto;
  left: 0;
  right: auto;
  max-height: 100px;
  max-width: 150px;
}
<a>
  <img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSgWHIrKgS3d0VR8LASdW4cXFkM5rkWtFDNgw&usqp=CAU" alt="someLogo">
</a>

0 Answers
Related