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

Viewport Width in sizes

Using vw units in sizes to describe images that scale with the viewport.

Viewport Width in sizes

You'll learn how to use vw units in the sizes attribute to describe images that fluidly scale with the viewport.


What Are vw Units?

The vw unit stands for "viewport width" — 1vw equals 1% of the browser window's width. If your viewport is 1000 pixels wide, 50vw means 500 pixels. These units are dynamic — they adjust automatically as the window resizes.

Using vw in the sizes Attribute

When you write sizes values, you can use vw units to tell the browser how much horizontal space your image will occupy relative to the viewport:

<img 
  srcset="small.jpg 400w, medium.jpg 800w, large.jpg 1200w"
  sizes="50vw"
  src="medium.jpg"
  alt="Scenic landscape">

This tells the browser: "This image will be displayed at 50% of the viewport width." The browser then selects the most appropriate image from srcset based on both the screen's actual width and pixel density.

Why This Matters

Instead of guessing fixed pixel widths, vw units reflect your actual CSS layout. If your image truly takes up half the screen width across all devices, 50vw is more accurate than writing (min-width: 600px) 600px, 400px with multiple breakpoints.

Think of it like a rubber band that stretches and shrinks with the window — the browser always knows the real display size.

Key Takeaway: Use vw units in sizes when your image scales proportionally with the viewport, giving the browser precise information to select the optimal source from srcset automatically.