Picture Tag in HTML

Learn via video course
FREE
View all courses
JavaScript Course With Certification: Unlocking the Power of JavaScript
JavaScript Course With Certification: Unlocking the Power of JavaScript
by Mrinal Bhattacharya
84669
4.8
Start Learning
JavaScript Course With Certification: Unlocking the Power of JavaScript
JavaScript Course With Certification: Unlocking the Power of JavaScript
by Mrinal Bhattacharya
84669
4.8
Start Learning
Topics Covered

Overview

The <picture> tag is used to give flexibility to web developers to display responsive images for different devices or screen sizes.

It is used to output or renders multiple images using the source tag or the <img> tag. It is typically utilized in situations when you wish to produce different-sized pictures based on the width of the screen or the size of the image. HTML5 introduces the picture tag.

Pre-requisites

Important to have : HTML Tags
Nice to have :

  • <img> tag,
  • <source> tag

Picture Tag in HTML

The HTML <picture> tag is a responsive images method that provides multiple sources to its contained img element. This enables authors to declaratively control or give hints to the user agent about which image resource should be used, taking into consideration the screen pixel density, viewport size, media query, support for a particular image format, and other factors.

picture-tag-in-html-1

As illustrated in the animation above, the image is not cropped when the screen dimensions change and instead varies in height and width based on the aspect ratio of the screen.

The picture tag is a container tag, i.e, it contains the opening tag, content, and closing tag.

Syntax :

The <picture> HTML element contains zero or more <source> elements and one <img> element to give alternate versions of an image for different display/device settings.

The browser will examine each child <source> element and choose the best match among them.

The <img> element is used as the last child element of the picture declaration block to ensure backward compatibility for browsers that don't support it or if none of the source tags match. The picture tag will not operate unless there is an img element nested within it.

The user agent checks the srcset, media, and typical characteristics of each <source> to choose a suitable picture that best suits the current layout and capabilities of the display device.

The <img> element serves two purposes :

  1. It specifies the image's size and other attributes, as well as its presentation.
  2. It acts as a fallback if none of the available <source> components can supply an acceptable picture for the webpage.

Let's understand the concept through code :

Note :
The <picture> tag is similar to <video> and <audio>. Various sources are added, and the first source that matches the preferences will be utilized.

Use Cases

Instead of having one image resized depending on the viewport width, the picture> element enables you to provide several images to more correctly fill the browser viewport.

It can be used for the following purposes :

  1. Art direction :
    Using the <picture> element, the landscape image is completely shown in the desktop layout and can be cropped or adjusted for various media conditions.

    use-cases-picture-tag-in-html

  2. Offering various image formats :
    When specific image formats aren't supported, the picture element provides alternate image formats. It works particularly well with modern image formats like webp and avif, providing a simple and effective way to minimize page size and enhance user experience.

Note :
Newer formats, such as AVIF or WEBP, offer several benefits, but certain browsers, such as Safari, Edge, and others, may not support them.

  1. Bandwidth :
    By loading the most relevant picture for the viewer's display, it saves bandwidth and speeds up page load times.

Attributes

Picture element only includes global attributes. Attributes applicable to the source and img tags will apply to the picture tag.

AttributeDescription
srcIt specifies the path or URL to the image
srcsetIt specifies a list of image files to use in different browser situations
mediaIt accepts a media query evaluated for each <source> tag
sizesIt defines a set of media queries with a width descriptor.
typeIt specifies a MIME type for resource URL
  • src :
    This attribute is used along with the <img> tag. It enables you to provide the image's path or URL to be shown on the website. This field is required and needs to be specified whenever a picture tag is used.
  • srcset :
    This attribute is new in HTML5 and can be used with both the <source> and <img> tags. The srcset property is identical to the src attribute, except it enables a greater number of values to be specified. It accepts two values as input : the first is a file's path or URL, and the second is either an image's width descriptor or a pixel density descriptor, both of which are followed by w and x, respectively.
  • media :
    This attribute is used along with the <source> tag which allows us to define the criteria on which the image will be displayed. It accepts any media query as input.

Note : Do not use the media attribute, unless art direction is required.

  • sizes :
    This attribute can be used with both <source> and <img> tags. It specifies a single-width descriptor, a single media query with a width descriptor, or a set of media queries with a width descriptor separated by commas. This is a new attribute in HTML5. The media condition is a simple condition like max-width: 800px without any additional parameters. The size attribute can accept more than one media condition like this. This is particularly helpful in responsive web design, where criteria may be established to show pictures appropriately.
  • type :
    Defines the MIME type of file chosen to be displayed. This attribute is used along with the <source> tag.

Note :
In a <source> element, you can only refer to images of the type declared in the type.

Usage

The <picture> element contains one or more <source> elements, each of which refers to a distinct image through the srcset attribute. This allows the browser to choose the most appropriate picture for the current view and/or device.

Each <source> element has a media attribute that defines when the image is the most suitable.

The object-position property, which is used to alter the positioning of the image inside the element's frame, and the object-fit property, which controls the image resizing within the frame, are both used by the Picture element to indicate how an object (image or video) should fit within the frame.

object-fit options include contain (fit according to aspect ratio), fill (stretches object to fill), and cover (overflows box but maintains ratio).

Note :
Use these properties on the child <img> element, not the <picture> element.

Examples

These examples show how different attributes of the <source> element change the selection of the image inside <picture>.

1. Basic Use of "picture" Tag :

This method is the simplest way to create responsive images and give more versatile viewport sizes and layouts using the picture tag.

Edit on Codepen and play with pictures by using the slider.


2. Using the "media" Attribute :

The media attribute specifies a media condition (similar to a media query) that the user agent will evaluate for each <source> element.

If the media condition of the <source> evaluates to false, the browser skips it and moves on to the next element in the <picture>.


3. Using the "srcset" Attribute :

For providing higher-density versions of an image for a high-DPI (Retina) display, use srcset on the <img> element. This lets browsers opt for lower-density versions in data-saving modes, and developers can avoid providing explicit media requirements.

It consists of a list of image descriptors separated by commas.

Each image descriptor consists of the picture's URL and one of the following :

  • a width descriptor, followed by a w (such as 300w), OR
  • a pixel density descriptor, followed by an x (such as 2x) to provide a high-res image for high-DPI displays.

4. Using the "type" attribute :

The type attribute defines the MIME type for the resource URLs in the srcset attribute of the <source> element. The <source> element is skipped if the user agent does not support the specified type.

Why "picture" Tag Should be Used Instead of the "img" Tag ?

reason-for-using-picture-tag-instead-of-img-tag

The <img> tag, as we all know, has long been one of the most important components in HTML, and its simplicity and utility have never been doubted.

However, as devices with varying screen sizes, resolutions, and demanding user needs become more common, concerns regarding their responsiveness and ability to be utilized in multi-device applications have arisen.

On the current web, the old-school <img> element with a single source URL does not perform properly. To speed up mobile layouts requires us to compromise picture resolution. It also compels us to think of new ways to adapt this compromised, unified picture to several displays to better highlight the image's focus points.

Featureimg tagpicture tag
Resolution switching using srcset and sizes attributesUsing image tags for high-resolution images causes performance concerns for devices with lesser screen resolutions, such as mobile phones.
This might lead to longer picture loading times and partial image loading from top to bottom.
For resolution switching, the picture tag uses the srcset and sizes properties.
The srcset property allows many pictures, each with its width in pixels, which the browser uses to pick amongst them.
The sizes property specifies how much display space the picture will occupy on the screen.
Art Direction using the media attributeWhile transitioning from a bigger screen to a mobile device, a picture that appears great on a larger screen may be cropped or seem too tiny.We can provide different versions of the image for different screen sizes. These different versions can be landscape, portrait, or any customized version of the same image.
If the screen is in landscape mode, the pictures from the first image set will be shown, and if it is in portrait mode, the photos from the second image set will be displayed. You may also utilize the media property with the max-width and min-width arguments.
Alternative image formatsAs technology moves quickly forward, new types of modern images are being made all the time. Some of these file types, like webp, SVG, and avif, give users a better experience.
But some browsers have limits on these modern image types, and things will go wrong if we don't use image types that are compatible with those browsers.
As the picture tag allows the inclusion of multiple sources inside it. It supports modern image formats like avif, and webp, which are highly responsive.

Additional advantages for picture tags include the support for partially supported image formats and Chrome DevTools support.

Using the "img" tag to display images on the webpage :


Using the "picture" tag to display images on the webpage :

In the above examples, the image gets cropped on changing the screen size when added via the img tag. Whereas, the picture tag adjusts the image resolution by changing the screen size.

Accessibility Concerns

The first source specifies a picture in the new AVIF format. If the browser can render AVIF pictures, that image file is selected. Otherwise, it moves on to the next source element.

The second source element refers to a WebP-formatted picture. The image file will be used if the browser is capable of handling WebP pictures.

Otherwise, the browser will use the image file specified in the img element's src attribute. That image is a JPEG.

As a result, you can experiment with new picture formats while ensuring backward compatibility.

The type property in that case tells the browser what sort of image format was given.

Browser Compatibility

The picture tag is supported by various browsers :

  • Google Chrome 38.0
  • Edge 13.0
  • Firefox 38.0
  • Opera 25.0
  • Safari 9.1
  • Samsung Internet 4.0

Note :
Some popular browsers like Internet Explorer and Opera Mini do not support the picture tag in HTML5.

Conclusion

  • Web developers use HTML picture tags in responsive web page designing.
  • The HTML <picture> element consists of two child tags source and img.
  • The <picture> element is used to implement an art direction picture switcher.
  • Using different attributes like srcset and sizes enables resolution switching to display images dynamically depending on the conditions.
  • CSS attributes like object-position and object-fit give control of positioning and resizing of the image, making the picture element highly responsive.
  • Due to its low bandwidth usage, cross-browser compatibility, and availability of features like cropping and modifying images, a picture tag is preferred use over an img tag.