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

Writing Effective sizes Values

Combining media conditions with width values to accurately describe image layout.

Writing Effective sizes Values

You'll learn how to accurately describe your image's display width under different conditions using the sizes attribute.

The Core Problem

When you use srcset with width descriptors, the browser knows the file sizes but doesn't know how large the image will appear in your layout. Will it fill the whole screen? Half? A sidebar? The sizes attribute tells the browser: "Here's how wide this image will be displayed, depending on the viewport."

Plain English Explanation

Think of sizes as instructions to a delivery service: "If the screen is small, deliver the 100%-width pizza box. If it's medium, deliver the 50%-width box. If it's large, deliver the 300px box." You're providing conditional display widths so the browser can pick the right source file.

The sizes attribute uses media conditions (like media queries) paired with width values:

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

Read it like: "If viewport ≤600px, image displays at 100% viewport width. If ≤1000px, it's 50% viewport width. Otherwise, it's fixed at 400px."

The browser evaluates conditions top to bottom and stops at the first match. The last value (no condition) is the default.

Common Patterns

  • Full-width hero: sizes="100vw"
  • Two-column grid: sizes="(min-width: 768px) 50vw, 100vw"
  • Sidebar thumbnail: sizes="(min-width: 1024px) 300px, (min-width: 768px) 200px, 150px"

Key Takeaway: Use sizes to mirror your actual CSS layout breakpoints and image widths, combining media conditions with accurate viewport or pixel measurements so the browser can select the optimal image source.