htmlresponsive-imagessrcsetpicture-element

Responsive picture element downloading correct size image from srcset


Based on the below picture tag, how does the browser determine which of the three files in the srcset attribute to download? My understanding is that the browser will determine which of the three (300px, 600px or 800px) based on the width of the viewport. The sizes attribute determines, based on the media condition, how big to display the image and not which image to send to the browser.

Is there a way to direct the browser which size to use?

<picture>
  <source srcset="~/images/300px.png 300w,
          ~/images/600px.png 600w,
          ~/images/800px.png 800w" 
          sizes="(min-width: 60rem) 80vw,
           (min-width: 40rem) 90vw,
           100vw">
  <img src="~/images/300px.png" alt="Image description">
</picture>


Solution

  • From the documentation:

    The browser will:

    1. Look at its device width.
    2. Work out which media condition in the sizes list is the first one to be true.
    3. Look at the slot size given to that media query.
    4. Load the image referenced in the srcset list that has the same size as the slot or, if there isn't one, the first image that is bigger than the chosen slot size.