Join the AI Workshop to learn more about AI and how it can be applied to web development. Next cohort February 1st, 2026
The AI-first Web Development BOOTCAMP cohort starts February 24th, 2026. 10 weeks of intensive training and hands-on projects.
Modern websites need to serve different image sizes for different devices. HTML provides two main approaches: the srcset attribute and the picture element.
Using srcset
The srcset attribute allows you to specify multiple image sources that the browser can choose from based on the screen size or pixel density:
<img src="dog.png"
alt="A picture of a dog"
srcset="dog-500.png 500w,
dog-800.png 800w,
dog-1000.png 1000w,
dog-1400.png 1400w">
The w descriptor indicates the width of each image in pixels. The browser uses this information to download only the appropriate image.
The sizes Attribute
When using srcset with width descriptors, you should also use the sizes attribute to tell the browser how large the image will be displayed:
<img src="dog.png"
alt="A picture of a dog"
sizes="(max-width: 500px) 100vw, (max-width: 900px) 50vw, 800px"
srcset="dog-500.png 500w,
dog-800.png 800w,
dog-1000.png 1000w,
dog-1400.png 1400w">
This sizes string means:
- If viewport is ≤ 500px: image will be 100% of viewport width
- If viewport is ≤ 900px: image will be 50% of viewport width
- Otherwise: image will be 800px wide
The picture Element
The picture element gives you more control over which image to serve. It’s ideal when you want to:
- Serve different image formats (like WebP with a fallback)
- Show completely different images at different screen sizes
<picture>
<source type="image/webp" srcset="image.png">
<img src="image.jpg" alt="An image">
</picture>
This serves a WebP image to browsers that support it, with a JPEG fallback for older browsers.
Using Media Queries with picture
You can use the media attribute on source elements to serve different images based on viewport size:
<picture>
<source media="(min-width: 1000px)" srcset="large-dog.jpg">
<source media="(min-width: 500px)" srcset="medium-dog.jpg">
<img src="small-dog.jpg" alt="A dog image">
</picture>
The browser uses the first source whose media query matches. The img tag serves as the fallback.
When to Use Each Approach
- Use srcset when you’re serving the same image at different sizes
- Use picture when you need to serve different images entirely (art direction) or different formats