Home > other >  HTML IMG: What is the benefit of setting an explicit width and height attribute within the HTML mark
HTML IMG: What is the benefit of setting an explicit width and height attribute within the HTML mark

Time:10-21

What is the benefit of explicitly defining a width and height attribute for an IMG element? I can set width to 100% via CSS and unless I explicitly set the height via CSS then the image element will retain the intrinsic aspect ratio. Conversely I can define a width and height attribute in the HTML markup and omit the CSS declaration and the image will just render at those explicit dimensions. Why set the dims in HTML if you are going to subsequently set width to 100% via CSS?

CodePudding user response:

Google recommend to set image size to avoid CLS (Cumulative Layout Shift). Read more https://web.dev/cls/

CodePudding user response:

Someone may have a better answer, but perhaps to provide more functionality... you can still use object-fit as I understand to retain the aspect ratio.

CodePudding user response:

The width and height attributes have been given a new lease of life - they can be set and subsequently used to set the CSS aspect-ratio of the replaced element. This helps avoid problems the browser has of sizing things before they are loaded.

See MDN for a fuller explanation, in particular:

This article explains a change that has occurred in the way sizes are worked out on web documents when width and height attributes are set on them.

This change means that the aspect ratio of the image is calculated by the browser early on and can then be used to correct the size needed to display the image before it has loaded

You can set the aspect ratio in CSS by:

aspect-ratio: attr(width) / attr(height);
  • Related