An essential aspect of web development is ensuring that images render quickly and fit properly across devices of all sizes. This comprehensive guide teaches you how to use the HTML <picture> tag to define responsive images for your website.



Example:

<picture>
   <source media="(min-width: 1200px)" srcset="large.jpg" type="image/jpeg">
   <source media="(min-width: 800px)" srcset="medium.jpg" type="image/jpeg">
   <img src="default.jpg" alt="Example image">
</picture>

What Is the HTML <picture> Tag?

The HTML <picture> tag is an essential element for responsive web design. It lets developers specify multiple source files for an image, allowing the browser to choose the most appropriate file based on the current viewport, screen resolution, and other factors.

How Does the <picture> Tag Work?

The <picture> tag works in conjunction with the <source> and <img> tags. Here's how these tags work together:

  • The <picture> tag is a container that wraps the structure. It tells the browser that an image with multiple source files is available.
  • The <source> tag is used to specify different image files. Each <source> tag includes a media attribute specifying the conditions for using that source file.
  • The <img> tag is a default image. It is used if none of the <source> tags match the current conditions.

<picture> Vs. <img> Tag

The question may be, "Why not just use the <img> tag?" The <img> tag is excellent with a single image source. But concerning responsive design, the <picture> tag provides more flexibility by allowing multiple sources to be specified.

<img src="default.jpg" alt="Example image">

Although the <img> tag is simpler to use, it does not provide the same control over how the image is displayed on different devices or browser sizes as the <image> tag.

Attributes of the <picture> Tag

The <picture> tag doesn't have any particular attributes; instead, it works in conjunction with <source> and <img> tags that have attributes. The following are the attributes related to these tags:

Attribute Tag Description
srcset <source>, <img> It defines one or more image sources  (versions of an image). The browser can choose the most appropriate of these based on current conditions.
sizes <source>, <img> It specifies the display sizes of the image for different viewport conditions, aiding the browser in choosing the most suitable image from the srcset attribute.
media <source> It specifies a media query. The corresponding source is used if the media query matches the current viewport size.
type <source> It defines the MIME type of the image source.
src <img> It specifies the path to the default image source. This image is displayed if none of the conditions are met in the <source> tag.
alt <img> It provides an alternate text description of the image. It is displayed when the image cannot be loaded for any reason.


Found This Page Useful? Share It!
Get the Latest Tutorials and Updates
Join us on Telegram