In the last lesson, you gave the hero photo four widths with srcset and sizes, so the browser can choose a smaller file when the slot and the screen don’t need the 1600-pixel one. However, every one of those files is still a JPEG. Newer image formats store the same photo in noticeably fewer bytes, and over a mobile data connection, every byte counts.
On a phone, the hero has a second problem too. Its wide strip shrinks plot 7 to a short band.
In this lesson, you’ll wrap the hero in a <picture> element, offer AVIF and WebP files with the JPEG as the fallback, and give small screens a square crop of their own. Start with the formats.
Offer Newer Formats With a Fallback
JPEG dates from the early 1990s. AVIF and WebP are newer image formats that compress photos better. For example, the 800-pixel version of plot 7’s photo comes to about 140 kB as a JPEG, 107 kB as WebP, and 81 kB as AVIF, at a similar quality. Your own numbers will depend on the quality setting you choose, but AVIF is usually the smallest.
Make each new file from the full-size original, as you did for the JPEGs in the last lesson. Don’t convert the JPEGs themselves. Every JPEG has already lost some detail to compression, and converting it again would carry those flaws into the new file. Squoosh is a free image converter that runs in the browser, so there’s nothing to install:
- Open Squoosh in Chrome and drop the full-size
plot-7.jpgfrom yourhtml-css-garden-photos-fullfolder onto the page. - In the panel on the right, turn on Resize and type
480into Width, then choose AVIF as the format. Click the download button, rename the fileplot-7-480.avif, and save it ingarden-practice/images/. - Change Width to
800,1200, and1600in turn, downloading and renaming each file. Then do all four widths again with WebP.
You now have twelve files of the same photo: four widths in three formats. Why not add the AVIF files to the <img> element’s srcset? Because srcset describes each file’s width, or the pixel density it’s meant for, but it has no way to say which format a file is in. The browser assumes it can display every file in the list. A browser that can’t decode AVIF would download one anyway and show a broken image.
The <picture> element lets you say “use these files only if you understand this format.” It wraps an ordinary <img>, and before the <img>, you list <source> elements.
Each <source> offers a set of files, and its type attribute names their format as a MIME type, such as image/avif. A MIME type is the label a server sends to say what kind of file it’s sending.
In garden-practice/index.html, wrap the hero’s <img> in a <picture>, and add two sources above it: