The sizes Attribute — Telling the Browser How Big Your Image Will Be
Understand the sizes attribute for responsive images: syntax, media conditions, and how to calculate correct values for your layout.
Detailed Explanation
Understanding the sizes Attribute
The sizes attribute is the missing piece that makes srcset truly effective. It tells the browser how wide the image will be displayed at various viewport widths — before the image is downloaded.
Syntax
The sizes attribute accepts a comma-separated list of media conditions paired with length values:
sizes="(max-width: 640px) 100vw,
(max-width: 1024px) 50vw,
33vw"
This reads: "Below 640px viewport, the image is 100% of viewport width. Below 1024px, it's 50%. Otherwise, it's 33%."
How the Browser Uses sizes
- The browser evaluates each media condition left to right
- The first matching condition's length is used
- The last entry (without a condition) is the default
- This length, combined with the device pixel ratio, determines which
srcsetimage to download
Common Patterns
| Layout | sizes Value |
|---|---|
| Full-width image | 100vw |
| Two-column grid | (max-width: 768px) 100vw, 50vw |
| Three-column grid | (max-width: 640px) 100vw, (max-width: 1024px) 50vw, 33vw |
| Fixed-width sidebar | (max-width: 768px) 100vw, calc(100vw - 300px) |
| Card in grid | (max-width: 640px) 100vw, (max-width: 1024px) 50vw, 25vw |
Common Mistake
The most common mistake is omitting sizes entirely. Without it, the browser defaults to 100vw, which means on a 1440px desktop viewport with 2x DPR, the browser would look for a 2880px-wide image — even if the image only displays at 400px wide. This wastes enormous bandwidth.
Using calc()
You can use calc() for more precise values:
sizes="(max-width: 768px) calc(100vw - 2rem), calc(50vw - 3rem)"
This accounts for padding and gutters in your layout.
Use Case
Critical for any layout where images are not full-width. Getting the sizes attribute right can mean the difference between downloading a 200KB image and a 2MB image on desktop layouts with multiple columns.
Try It — Responsive Image Srcset Generator
Related Topics
The srcset Attribute Explained — Width Descriptors and Resolution Switching
Fundamentals
The picture Element — Format Negotiation with source Tags
Fundamentals
Responsive Images in CSS Grid and Flexbox Layouts
Use Cases
Common srcset and sizes Mistakes — How to Avoid Them
Best Practices
Hero Image Responsive Markup — Optimize for LCP
Best Practices