Course contentsShow
← Web Development
Lesson 2008 of 2,98237. Image and Asset OptimizationFree lesson

The srcset Attribute for Resolution Descriptors

Use srcset with width descriptors (w) to provide multiple image sources for different viewport widths.

The srcset Attribute for Resolution Descriptors

You'll learn how to serve appropriately sized images to different screen widths using the srcset attribute with width descriptors.

Modern devices come in wildly different screen sizes—from smartphones to 4K monitors. Serving the same large image to all devices wastes bandwidth on small screens and slows down your site. The srcset attribute solves this by letting you specify multiple image sources, and the browser picks the best one based on the user's viewport width.

How srcset with Width Descriptors Works

Instead of loading one massive image everywhere, you provide several versions of the same image at different resolutions. Use the w descriptor to tell the browser each image's actual width in pixels:

<img 
  src="photo-800w.jpg" 
  srcset="photo-400w.jpg 400w,
          photo-800w.jpg 800w,
          photo-1200w.jpg 1200w"
  alt="A scenic landscape">

Here's what happens:

  • photo-400w.jpg 400w tells the browser this image is 400 pixels wide
  • photo-800w.jpg 800w indicates an 800-pixel-wide version
  • photo-1200w.jpg 1200w provides a 1200-pixel-wide option

The browser considers the viewport width, device pixel ratio, and network conditions to automatically select the most appropriate image. A phone user gets the 400w version, while a desktop user might receive the 1200w version.

Think of It Like Restaurant Portions

Imagine ordering food: a child gets a small portion, an adult gets medium, and an athlete gets large. You wouldn't serve everyone the same oversized plate—it wastes food. Similarly, srcset serves "right-sized" images, avoiding wasted bandwidth.

Key Takeaway: Use srcset with w descriptors to provide multiple image resolutions, letting browsers automatically select the optimal file size for each user's device and viewport.