Does `size` need to be used with `srcset`, what are the pros / cons?

992 views Asked by At

Does size need to be used with srcset ? Ive got a site that has a large image pretty much full screen apart from a 50px board all the way round. The proportion of this image dosnt need to change depending upon different screen proportions / sizes.

At the moment im using just srcset like this :

<img 
src="bath.jpg"
srcset="bath-large.jpg 1500w, bath-medium.jpg 1000w, bath-small.jpg 600w"
alt="#"
>

The issue with this is that if a user is on a desktop opens up the site in a compressed browser (so the small image will be loaded) then makes their browser window bigger, the small image will just be scaled so it will now be pixilated. (If they refreshed the page they would now get the large or medium image, but i doubt any one would refresh the page after every resize of a browser window)

By using the size attribute would it then try are recalculate which image to use if the browser window is resized ? If not what is the use case for the size attribute ?

2

There are 2 answers

2
giraff On BEST ANSWER

The sizes-Attribute (note the s) can help the browser decide which resolution to load. At the time of choosing the resolution, the CSS might not be rendered yet, so we need to duplicate this information.

It declares to the browser which space the image will have in the layout. It defaults to "100vw" which means "the width of the viewport", which is a sane default because the image probably will not be shown bigger than that, so in the worst case, an image is loaded whose resolution is too big (better than too small).

The sizes-Attribute thus makes sense when you use a fluid layout with images that do not span over the whole viewport width, probably depending on breakpoints. For example, sizes="(min-width: 900px) 33.3vw, 100vw" would mean that the image is in a 3-column-layout when the browser viewport is bigger than 900px (or 450px and a 2dpi-Retina-Screen, etc.).

You can find a great article about the math details here.

In your case, sizes doesn't help (although you could write sizes="calc(100vw - 100px)". Re-downloading a bigger resolution is something the browser needs to decide, and this might be implemented differently by each browser. Chrome currently does (however it does not do the inverse, as soon as a high resolution is downloaded the lower resolutions are ignored as 'not necessary').

0
Wojciech Maj On

The size you specify in srcset is for a case when the image is responsive, in other words, when the image does not have a fixed with.

If the image is resized, the browser that supports srcset will try to find a source image from srcset that fits best.