The picture tag gives more flexibility in specifying image resources.
The most common use of the picture element will be in responsive designs.
Instead of having one image we can add multiple images to fill the browser viewport.
The picture element holds two different tags:
1. one or more source tags and
2. one img tag to offer alternative versions of an image for different devices/screens.
To decide which URL to load, the user agent examines each source‘s srcset, media, sizes and type attributes to select a compatible image that best matches the current layout and capabilities of the display device.
The source element has the following attributes:
1. srcset (required) – defines the URL of the image to show
2. media – accepts any valid media query that would normally be defined in a CSS
3. sizes – defines a single width descriptor, a single media query with width descriptor, or a comma-delimited list of media queries with a width descriptor
4. type – defines the MIME type
The browser will use the attribute values to load the most appropriate image.
The browser will use the first source element with a matching hint and ignore any following source tags.
If no matches are found—or the browser doesn’t support the picture element—the URL of the img element’s src attribute is selected.
The img element is required as the last child tag of the picture declaration block.
The img element is used to provide backward compatibility for browsers that do not support the picture element, or if none of the source tags matched.
The picture element works similar to the video and audio elements.
You set up different sources, and the first source that fits the preferences is the one being used.
You can use the object-position property to adjust the positioning of the image within the element’s frame, and the object-fit property to control how the image is resized to fit within the frame.
Examples
The media attribute
<picture>
<source srcset="logo-wide.png" media="(min-width: 600px)">
<img src="logo-narrow.png" alt="logo">
</picture>
The srcset attribute
<picture>
<source srcset="logo-768.png 768w, logo-768-1.5x.png 1.5x">
<source srcset="logo-480.png, logo-480-2x.png 2x">
<img src="logo-320.png" alt="logo">
</picture>
The type attribute
<picture>
<source srcset="logo.webp" type="image/webp">
<img src="logo.png" alt="logo">
</picture>
html tags images picture