<picture>

The <picture> element provides responsive images by defining multiple sources with media queries, optimizing display for various devices and resolutions.

<picture> Tag

The <picture> element allows defining multiple <source> elements for an <img> tag. This helps the browser select the best-suited image based on the screen size or resolution, improving loading efficiency and responsiveness.

Syntax

index.html
<picture>
  <source srcset="image-/placeholder.jpeg" media="(max-width: 600px)">
  <img src="/placeholder.jpeg" alt="Description of the image">
</picture>

<picture> Demo

Responsive Image
index.html
<picture>
  <source srcset="img.jpg" media="(max-width: 600px)">
  <img src="img.jpg" alt="Responsive Image">
</picture>

Key Points

  • Purpose: Enables different image sources for varying screen sizes and resolutions.
  • Elements:
    • <source>: Defines alternate image sources using srcset and media attributes.
    • <img>: Serves as a default image if no <source> matches.

Attributes

  • srcset: Specifies one or more image sources for the <source> element.
  • media: Defines a media query that determines when a specific source should be used.

Conclusion

The <picture> tag provides a versatile and responsive approach to handling images in HTML. By defining multiple <source> elements, you can optimize image delivery based on different screen sizes and resolutions, improving both performance and user experience.