Understanding of the HTML picture element

Published on 10/8/2023

Last update on 10/8/2023

Introduction

In general, three factors matter for better images: format, size and behaviour.

Following is an example of the HTML picture element:

<picture>
  <source type="image/avif"
          srcset="/Images/cli--FhskL-300.avif 300w,
                  /Images/cli--FhskL-600.avif 600w,
                  /Images/cli--FhskL-900.avif 900w"
          sizes="(min-width: 45rem) 50vw, 100vw" />
  
  <source type="image/webp" 
          srcset="/Images/cli--FhskL-300.webp 300w,
                  /Images/cli--FhskL-600.webp 600w,
                  /Images/cli--FhskL-900.webp 900w"
          sizes="(min-width: 45rem) 50vw, 100vw" />

  <source type="image/jpeg"
          srcset="/Images/cli--FhskL-300.jpeg 300w,
                  /Images/cli--FhskL-600.jpeg 600w,
                  /Images/cli--FhskL-900.jpeg 900w"
          sizes="(min-width: 45rem) 50vw, 100vw" />

  <img alt="…" loading="lazy" decoding="async"
       src="/Images/cli--FhskL-300.jpeg" width="3264" height="1962" />
</picture>

Here, we defined three formats among which the browser can choose: AVIF, WebP and JPEG. For each of them, we specified the srcset for the sources where to find the image files, and the sizes attribute, a kind of media query.

sizes

The above code means: we provide an image with three formats, putting better formats first to take advantage of better and modern compression technologies. For each format, we provide three sizes, 300w, 600w and 900w. The browser follows ours order to select the best one, using sizes. Following the example, in a one DPI display, below 720 pixels (the standard for 45rem), we’re telling the browser to be aware that the picture will take the full screen (100vw). So:

Always in a one DPI display, above 720 pixels (the standard for 45rem), we’re telling the browser to be aware that the picture will take half the screen (50vw). So:

DPI matters

In a two DPIs display, everything goes “times 2”, so, in a tablet device with a width of 800px, the picture will need to satisfy the 800/2*2=400*2=800 rule, so the “900” version will be taken, because the browser chooses the next higher one better than the “600” version (the “600” version would be blurry in a two DPIs display, so the browser takes the first version that satisfies the size).

← Return to blog