Home > OS >  How to specify image width/height correctly to avoid CLS?
How to specify image width/height correctly to avoid CLS?

Time:10-30

My image now: <img src="image.webp" width="100%">

I know, I should use this to prevent cumulative layout shift: <img src="image.webp" width="150" height="200">

But this way it can't fill the div in all screen resolutions, so it is not responsive anymore.

What should I do?

Thank you.

CodePudding user response:

You are probably looking for the css properties max-width and max-height. They will prevent the image from getting any bigger that the width and height you specify, but if the viewport is too small and the would overflow, then they default to the regular width and height, which if not declared would default to auto (but you can also use the width="100%" that you are already using, which is also responsive) and fit on your screen.

You probably want something more robust to make your entire layout re-arange nicely, but max width and height are a good place to start looking

  • Related