What is picture Tag?
Normally, we use the <img> tag to display an image on a webpage. But sometimes one image is not enough because the same image may look good on a computer but not on a mobile phone. The <picture> tag solves this problem. It allows us to keep different versions of the same image and lets the browser choose the best one depending on the screen size. This helps the webpage look better on every device.
How It Works?
Inside the <picture> tag, we use one or more <source> tags and one <img> tag. The <source> tags contain different images with conditions, and the browser checks these conditions from top to bottom. When it finds the first matching condition, it displays that image. If none of the conditions match, the browser uses the image inside the <img> tag as the default image.
<picture>
<source srcset="mobile.jpg" media="(max-width:600px)">
<source srcset="tablet.jpg" media="(max-width:900px)">
<img src="desktop.jpg" alt="Nature">
</picture>
max-width and min-width
The media attribute decides when an image should be used. It mainly works with max-width and min-width.
-
max-widthmeans this width or smaller. -
min-widthmeans this width or bigger.
For example,
<source srcset="mobile.jpg" media="(max-width:600px)">
This means if the screen width is 600px or less, the browser will show mobile.jpg.
Another example,
<source srcset="desktop.jpg" media="(min-width:900px)">
This means if the screen width is 900px or more, the browser will show desktop.jpg.
Why <picture> Tag?
The <picture> tag makes a website more responsive. Mobile users can download smaller images, which helps the page load faster, while desktop users can see larger and clearer images. It also gives us more control over how images are displayed on different screen sizes.
Top comments (0)