DEV Community

ABISHEK M
ABISHEK M

Posted on

picture Tag in Html

What is <picture> Tag?

Normally, we use the <img> tag to display an image on a webpage. But sometimes one image is not suitable for every device. A large image may look perfect on a desktop, but it can be too large for a mobile phone, making the webpage slower to load. The <picture> tag solves this problem. It allows us to provide different versions of the same image, and the browser automatically chooses the most suitable one based on the screen size or other conditions. This helps create responsive and user-friendly websites.

How It Works

Inside the <picture> tag, we use one or more <source> tags and one <img> tag. Each <source> tag contains an image and a condition. The browser checks these conditions from top to bottom. When it finds the first condition that matches, it displays that image. If none of the conditions match, the browser displays the image inside the <img> tag as the default or fallback image.

<picture>
    <source srcset="mobile.jpg" media="(max-width:600px)">
    <source srcset="tablet.jpg" media="(max-width:900px)">
    <img src="desktop.jpg" alt="Nature Image">
</picture>
Enter fullscreen mode Exit fullscreen mode

Output

  • If the screen width is 600px or less, mobile.jpg is displayed.
  • If the screen width is between 601px and 900px, tablet.jpg is displayed.
  • If the screen width is greater than 900px, desktop.jpg is displayed.

max-width and min-width

The media attribute decides when an image should be displayed. It commonly uses max-width and min-width.

  • max-width means this width or smaller.
  • min-width means this width or larger.

Example 1

<source srcset="mobile.jpg" media="(max-width:600px)">
Enter fullscreen mode Exit fullscreen mode

This means if the screen width is 600px or less, the browser displays mobile.jpg.

Example 2

<source srcset="desktop.jpg" media="(min-width:900px)">
Enter fullscreen mode Exit fullscreen mode

This means if the screen width is 900px or more, the browser displays desktop.jpg.

Why Use the <picture> Tag?

The <picture> tag makes a website more responsive by displaying the most suitable image for different devices. Smaller images are loaded on mobile phones, which improves page loading speed and saves internet data. Larger and high-quality images can be displayed on desktops for a better viewing experience.

Learning the <picture> tag is useful for beginners who want to build modern and responsive websites.

Top comments (0)