Skip to main content

HTML Picture Element

By SamK
0
0 recommends
Topic(s)

The HTML <picture> element can be used to display different images based on different devices or screen sizes.

Within the <picture> element, you can include multiple <source> elements, each referencing different images using the srcset attribute. This allows the browser to select the most appropriate image based on the current view or device.

Hence, the HTML <picture> element provides web developers with greater flexibility in defining image resources.

Each <source> element includes a media attribute that specifies the conditions under which the image is most suitable.

<picture>
    <source media="(min-width: 640px)" srcset="img1.jpg">
    <source media="(max-width: 639px)" srcset="img2.jpg">
    <img src="img_default.jpg">
</picture> 

In the above example, the first image will be selected when the minimum media width is 640 pixels. Similarly, the second image will be selected when the media width is less than 640 pixels.

When to Use

1. To Save Bandwidth

For smaller screens or devices, there's no need to load a large image file. In case of a <picture> element, the browser will select the first <source> element with matching attribute values and ignore the rest.

<picture>
    <source media="(max-width: 480px)" srcset="img1_sm.jpg">
    <source media="(min-width: 481px)" srcset="img1_lg.jpg"> 
    <img src="img_default.jpg"> 
</picture>

In the above example, the first image (smaller version) will be selected when the user is using a small media device of less than or equal to 480px width. Similarly, the second image (larger version) is selected when the user is using a larger media device having more than 480px width.

2. To Support Browsers

Not all browsers or devices support every image format. Utilizing the <picture> element allows you to include images in multiple formats. In case of the example below, the browser will select the first format it can display and disregard the others.

<picture>
    <source srcset="image.png">
    <source srcset="image.jpg">
    <source srcset="image.webp">
    <img src="image.gif">
</picture>