Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What do the width and height attributes do when using srcset and sizes?

If we're using the srcset and sizes attributes, it is still useful to specify a src attribute as a fallback. Similarly, I imagine that older browsers would also take advantage of width and height attributes if they were specified. But do modern browsers?

For example:

<img
   src="foo100x100.jpg"
   srcset="foo100x100.jpg 100w, foo500x500.jpg 500w, foo900x900 900w"
   sizes="100vw"
   width="100"
   height="100"
   alt="example"
>

Are the width and height attributes of any use to a modern browser in this example?

like image 283
Flimm Avatar asked May 09 '16 21:05

Flimm


People also ask

What do the width and height attributes do?

The height and width attribute in HTML is used to specify the height and width of the element. The values are set in px i.e. pixels. To add an image in an HTML page, <img> tag is used. With that, we need to use the attributes height and width to set the height and width of the image in pixels.

Why is it important to assign height and width attributes to an image?

Tip: Always specify both the height and width attributes for images. If height and width are set, the space required for the image is reserved when the page is loaded. However, without these attributes, the browser does not know the size of the image, and cannot reserve the appropriate space to it.

Do you need sizes with Srcset?

Using srcset with width ( w ) descriptors like this means that it will need to be paired with the sizes attribute so that the browser will know how large of a space the image will be displaying in. Without this information, browsers can't make smart choices.

What is the Srcset attribute?

The srcset attribute allows you to specify a list of image file URLs, along with size descriptions. Yo ualso need to still use the src attribute to identify a “default” image source, to be used in browsers that don't support srcset .


1 Answers

Based on experimentation, it behaves as if you had specified width and height CSS properties in pixels. However, it can be overridden by your own CSS.

img {
  width: 200px;
  /* height will be 100px because of the HTML attribute */
}
<img
     src="http://placehold.it/100x100"
     srcset="http://placehold.it/100x100 100w, http://placehold.it/500x500 500w"
     sizes="100vw"
     alt=""
     width="100"
     height="100"
>

This is a bit disappointing, as I was hoping that modern browsers would use width and height HTML attributes to determine what the aspect ratio of the image was before downloading the image, so as to avoid the layout of following content jumping around as the page loads.

like image 150
Flimm Avatar answered Oct 23 '22 03:10

Flimm