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

The sizes Attribute Fundamentals

Telling the browser how wide the image will be displayed at different viewport sizes.

The sizes Attribute Fundamentals

You'll learn how to tell the browser exactly how wide your image will be at different screen sizes, so it can pick the perfect file.

Why sizes Matters

When you provide multiple image sources with srcset, the browser needs to know something crucial: how much screen space will this image actually occupy? By default, the browser assumes your image will be 100% of the viewport width. But most images aren't that wide—they might be in a sidebar, a grid, or have max-widths applied.

The sizes attribute is your way of saying: "Hey browser, at this screen width, my image will be this wide."

How sizes Works

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

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

The browser reads this top-to-bottom:

  • If viewport is ≤600px wide → image displays at 100vw (full width)
  • Else if viewport is ≤1200px → image displays at 50vw (half width)
  • Otherwise → image displays at 33vw (one-third width)

The browser uses this info plus srcset to choose the most appropriate file before downloading anything.

Think of It Like a Menu

Imagine ordering at a restaurant: srcset lists all available dish sizes (small, medium, large), while sizes tells the waiter "I'm very hungry" or "I just want a snack"—helping them recommend the right portion.

Key Takeaway: The sizes attribute describes the image's display width at various viewport sizes, enabling the browser to select the optimal file from srcset before download.