The sizes Attribute
You'll learn how to tell the browser exactly how wide an image will display at different screen sizes, so it can pick the perfect image file.
What sizes Does
When you provide multiple image sources with srcset using width descriptors (w), the browser faces a puzzle: which image should it download? It knows the screen's resolution, but it doesn't know how much space your image will occupy on the page.
That's where sizes comes in. It gives the browser a "heads up" about the image's display width before the CSS has even loaded.
How It Works
The sizes attribute uses media conditions (like media queries) paired with length values:
<img
srcset="small.jpg 400w, medium.jpg 800w, large.jpg 1200w"
sizes="(max-width: 600px) 100vw,
(max-width: 1000px) 50vw,
33vw"
src="medium.jpg"
alt="Responsive image">
This tells the browser:
- On screens 600px or narrower: the image fills 100% of the viewport width
- On screens 601px–1000px: the image takes 50% of the viewport
- On larger screens: the image occupies 33% of the viewport
The browser reads these hints, calculates which image size it needs, and downloads the most appropriate file from srcset.
Think of It as a Menu
Imagine ordering food: srcset is the menu (all available options), and sizes is you telling the waiter "I want a small portion if I'm eating alone, medium if sharing with one person, large for a group." The kitchen (browser) then prepares exactly what you need.
Key Takeaway: The sizes attribute informs the browser how wide an image will display under different conditions, enabling smart selection from srcset options.