Course contentsShow
← Web Development
Lesson 1222 of 2,98222. Responsive Images and MediaFree lesson

Multiple Media Conditions in sizes

Chaining multiple breakpoints to handle different image widths across all viewport ranges.

Multiple Media Conditions in sizes

What you'll learn: How to chain multiple breakpoints in the sizes attribute so different image widths load across all possible viewport ranges.


The Need for Multiple Breakpoints

You've already learned to write a single media condition in sizes. But real websites serve many different layouts: mobile, tablet, desktop, and sometimes even larger displays. To match your responsive design perfectly, you need to specify multiple breakpoints that cover all viewport ranges.

Think of it like a chain of "if-then" statements: "If the viewport is this wide, use this image width; otherwise, if it's that wide, use a different width; otherwise, default to this."


Chaining Conditions with Commas

The sizes attribute accepts multiple conditions separated by commas. The browser reads them left to right and uses the first condition that matches.

<img
  srcset="small.jpg 400w, medium.jpg 800w, large.jpg 1200w"
  sizes="(max-width: 600px) 100vw, 
         (max-width: 1024px) 50vw, 
         33vw"
  src="medium.jpg"
  alt="Responsive image">

How it works:

  • On screens ≤600px: image fills 100vw (full width)
  • On screens 601px–1024px: image fills 50vw (half width)
  • On screens >1024px: image fills 33vw (one-third width)
  • The browser picks the closest matching image from srcset

Order Matters

Always put narrower breakpoints first, wider ones later. The browser stops at the first match, so ordering incorrectly causes wrong sizes to apply.

Key Takeaway: Chain multiple media conditions in sizes with commas to precisely control image width across all viewport ranges, ensuring the browser downloads the optimal file for every device size.