The sizes Attribute: Telling Browsers Image Display Size
You'll learn how to tell the browser exactly how much screen space your image will occupy, so it can pick the perfect image file from your srcset list.
What Problem Does sizes Solve?
When you provide multiple image sources with srcset, the browser knows what files are available and their widths. But it doesn't automatically know how big the image will appear on your page. Will it fill the full viewport? Half? A sidebar thumbnail? Without this information, the browser can't make the optimal choice.
How sizes Works
The sizes attribute uses CSS-like media queries to describe the image's display width at different viewport sizes:
<img
srcset="small.jpg 400w, medium.jpg 800w, large.jpg 1200w"
sizes="(max-width: 600px) 100vw,
(max-width: 1200px) 50vw,
33vw"
src="medium.jpg"
alt="Responsive photo">
This tells the browser:
- On screens ≤600px wide: image displays at 100% viewport width (
100vw) - On screens ≤1200px wide: image displays at 50% viewport width (
50vw) - On larger screens: image displays at 33% viewport width (
33vw)
The browser evaluates these conditions before downloading any image, then selects the smallest file from srcset that will still look sharp at that display size.
Think of It Like Ordering Clothes
You're shopping online. The store has the same shirt in S/M/L (your srcset). The sizes attribute is you telling them "I'll wear this for jogging (small), office work (medium), or a wedding (large)." They send the right size based on the occasion.
Key Takeaway: The sizes attribute tells browsers how much viewport space an image occupies at different breakpoints, enabling intelligent resolution switching from your srcset options.