The <picture> element in HTML is used to provide multiple versions of an image, allowing the browser to select and display the most appropriate image based on the device's capabilities and screen size. It is commonly used for responsive web design and optimizing images for different devices or display scenarios.

The <picture> element can contain one or more <source> elements, each specifying a different image source and conditions for when that source should be used. It also requires an <img> element as a fallback option in case none of the specified sources match the conditions.

Here's the basic structure of the HTML <picture> element:

<picture>
  <source srcset="image1.jpg" media="(condition1)">
  <source srcset="image2.jpg" media="(condition2)">
  <source srcset="image3.jpg" media="(condition3)">
  <img src="fallback.jpg" alt="Fallback Image">
</picture>

 

Let's explain the components:

  • <source>: The <source> element specifies the image source using the srcset attribute, which contains one or more image URLs separated by commas. Each source can have optional media queries defined using the media attribute to specify conditions for when that source should be used. Media queries can check properties like screen width, resolution, and other factors. The browser selects the first source whose conditions are met.

  • <img>: The <img> element serves as a fallback option and provides the source URL for browsers that do not support the <picture> element or if none of the <source> conditions are met. It is also used as the default image source for screen readers and search engines.

Here's an example of using the <picture> element to serve different images based on screen size:

<picture>
  <source srcset="image-large.jpg" media="(min-width: 800px)">
  <source srcset="image-medium.jpg" media="(min-width: 500px)">
  <img src="image-small.jpg" alt="Image">
</picture>

 

In this example, if the screen width is 800 pixels or more, the browser will load image-large.jpg. If the screen width is between 500 and 799 pixels, image-medium.jpg will be used. For screens below 500 pixels, the fallback image image-small.jpg will be loaded.

Using the <picture> element with multiple sources and media queries allows you to optimize image delivery and improve the user experience by providing appropriate images for different devices and display contexts.

Latest Tutorial

Newly published tutorials

How to Make an AWS S3 Bucket Public

Learn how we can make an AWS S3 bucket public

Laravel 10 - Send mail using AWS SES

Learn to send Email using Laravel 10 with AWS SES service.

Laravel 10 - Tutorial to create CRUD Application

Learn to create crud application using laravel 10. Step by step guidance will help to understand the concept of crud.