html
  1. html-picture-tag

HTML <picture> Tag

  • The HTML <picture> tag is used to include different image sources and their respective sizes for different device screen sizes or resolutions in a webpage.
  • This allows for a better user experience on different device types and sizes by displaying the most appropriate image according to the device's resolution.

Syntax

The basic syntax of the HTML <picture> tag is as follows:

<picture>
  <source srcset="image1.jpg" media="(min-width: 1200px)">
  <source srcset="image2.jpg" media="(min-width: 768px)">
  <source srcset="image3.jpg">
  <img src="default.jpg" alt="description of the image">
</picture>

Here, we define different sources for an image and their sizes by using the tag and set default image source by using <img> tag.

Example

Let's take an example of a responsive webpage that displays a different image for different screen sizes. The code looks like the following:

<picture>
   <source media="(min-width: 1200px)" srcset="image-large.jpg">
   <source media="(min-width: 768px)" srcset="image-medium.jpg">
   <source srcset="image-small.jpg">
   <img src="image-small.jpg" alt="description of the image">
</picture>
Try Playground

In this example, the first source is for a large screen size, the second source is for a medium screen size, and the third source is default for all other screen sizes.

Explanation

The <picture> tag is used to define a container for one or more <source> and <img> elements. The <source> tag is used to define the source of an image and the screen size for which it is intended. The srcset attribute is used to define the image source and associated sizes.

Use

The <picture> tag can be used for any image that needs to be optimized for various device types and sizes, especially when a website is designed for a responsive layout. By using this tag, we can benefit from faster page loading times while providing the best image quality for different devices.

Important Points

  • Use of <picture> tag is a better option than <img> tag for responsive web design.
  • Always use the 'alt' attribute for describing images.
  • Use the appropriate tag while declaring different image sources and sizes to provide a better user experience.

Summary

The HTML <picture> tag is a powerful tool for creating responsive images on webpages. By optimizing images for different devices resolutions, one can gain a better customer experience and faster loading times on different devices. The use of <picture> tag is a good practice modern web design.

Published on: