A pretty exhaustive overview of the HTML and CSS options that we now have for responsive image layouts. Here are some key takeaways:
- Prioritise
srcset
for the best performance gains,<picture>
for the greatest level of editorial control (think different images for dark mode, or completely different layouts on smaller/larger screens); - Setting the lowest resolution image within a
srcset
to thesrc
value is normally best; - The RespImageLint tool is very useful for determining
srcset
sizes
attributes; - There's also the LazySizes library for lazy-loading images;
- Despite clever tooling,
sizes
remain tricky to get right and often benefit from templating abstractions (as does the whole responsive image malarkey in total); - If you need to be able to zoom in on an image and serve a higher resolution image as it happens,
srcset
lets you achieve that by specifying widths wider than the viewport i.e.300vw
; - Art direction using the
<picture>
element can be used to serve static images instead of GIFs for users who prefer reduced motion (there are any interesting niche use cases with links out to full resources); - The
<picture>
element also provides a chance to use more performant image formats such as WebP, whilst providing a graceful fallback for older browsers; - You can combine
<picture>
andsrcset
if needed, which may net some further performance savings; - Netlify (and a bunch of other CDN services) offer automatic image resizing based on URL parameters;
- Don't forget the value of using
object-fit
andobject-position
to handle the bits in-between breakpoints as well; - There's also a huge list of further reading and sources at the end of the article.