📸 HTML Picture Tag
Learn how to serve different images for different devices and screen sizes
📚 What is the Picture Tag?
📌 Key Concept
The <picture> element gives web developers more flexibility in
specifying image resources. It allows you to define multiple <source> elements for different screen sizes (media queries) or image
formats, with a mandatory <img> tag as a fallback.
Why use <picture> instead of <img>?
- Art Direction: Cropping images differently for mobile vs desktop.
- Format Support: Serving modern formats like WebP to supported browsers while falling back to JPEG/PNG.
- Bandwidth Saving: Loading smaller images on smaller devices.
💻 Code Examples
📝 Example 1: Responsive Art Direction
Show a different image based on screen width (resize browser to see change):
<picture>
<source media="(min-width: 650px)" srcset="img_desktop.jpg">
<source media="(min-width: 465px)" srcset="img_tablet.jpg">
<img src="img_mobile.jpg" alt="Responsive image" style="width:auto;">
</picture>
▶️ Output:
📝 Example 2: Image Format Fallback
Serve WebP format to browsers that support it, and JPG to others:
<picture>
<source srcset="image.webp" type="image/webp">
<source srcset="image.jpg" type="image/jpeg">
<img src="image.jpg" alt="Format fallback example">
</picture>
▶️ Output:
🔧 Tag Attributes
<source> Attributes
| Attribute | Description | Example |
|---|---|---|
srcset |
URL of the image to use (Required in source) | srcset="img.jpg" |
media |
Media query condition (like CSS) | media="(min-width: 600px)" |
type |
MIME type of the image format | type="image/webp" |
Note: The <img> tag must always be the
last child of the <picture> element. It serves as
the fallback and is required for the image to render.
✍️ Practice Assignments
🎯 Assignment 1: Mobile vs Desktop
EasyCreate a picture element that switches images based on device width.
- Use a landscape image for desktop (min-width: 800px)
- Use a portrait/square image for mobile (default img)
🎯 Assignment 2: Modern Formats
MediumImplement format switching for better performance.
- Find a .webp image and a .jpg version of the same image
- Use <source> with
type="image/webp" - Ensure the fallback <img> points to the .jpg
🎯 Assignment 3: Dark Mode Image
HardUse the media attribute to serve different images based on system theme preference.
- Use
media="(prefers-color-scheme: dark)" - Show a light-themed image by default
- Show a dark-themed image when dark mode is active
🎓 Key Takeaways
- Use
<picture>for "Art Direction" (changing image content based on layout) - Use
<source>to define alternative image versions - Always include an
<img>tag as the last child - The browser stops searching after the first matching
<source> - Use
srcsetin source tags, notsrc