Using the <picture> Element for Different Screen Sizes
You can use HTML's picture element to serve different images based on various factors like screen size, resolution, or format. This element allows you to define multiple sources for an image and have the browser choose the most appropriate one for the current device.
The picture element is more advanced than the simple CSS responsive image technique. While CSS allows you to scale the same image file, the picture element allows you to deliver entirely different image files for different screen sizes, resolutions, or formats.
The Basic <picture> Syntax
To use the picture element for different screen sizes, you need to include one or more source elements and one img element:
How it works
- The
sourceelement: This is used to specify different versions of an image files. It uses themediaattribute to define the condition (such as screen width) under which that version should be used. - The
srcsetattribute: This specifies the URL of the image to show when the media condition is met. - The
imgelement: This is the last element in thepicturetag and is used as a fallback if the browser does not support thepictureelement, or if none of thesourceconditions are met.
Interactive Example
Below is a working example of a responsive image using the picture element:
In the preview window, try resizing the container or your browser window (if supported) to see the image change based on the width.
Art Direction vs. Resolution Switching
The picture element is often used for "art direction." For example, you might want a wide panoramic image on desktop, but a zoomed-in, cropped version of the same scene on mobile. The picture element makes this possible by allowing you to choose the best version of an image for each device.
Serving Different Image Formats
The picture element can also be used to deliver different image formats (like AVIF, WebP, or PNG) based on browser support, which can significantly reduce file sizes:
In this case, no media queries are required. The browser will simply choose the first image format it supports.