What You'll Learn
You'll learn how to use the srcset attribute to serve different image resolutions based on the user's screen pixel density, ensuring crisp images on high-resolution displays without wasting bandwidth on standard screens.
The Problem: One Size Doesn't Fit All
Imagine serving the same photograph to both a regular laptop and a high-resolution Retina display. On the Retina screen, your image might look blurry because it's being stretched to fill more physical pixels. But if you serve the high-resolution version to everyone, users on standard displays download unnecessarily large files.
How srcset Solves This
The srcset attribute lets you provide multiple versions of the same image at different resolutions. The browser automatically picks the most appropriate one based on the device's pixel density.
Think of it like a restaurant menu with small, medium, and large portions—the customer (browser) chooses what fits their appetite (screen capabilities).
Basic Syntax
<img src="photo.jpg"
srcset="photo.jpg 1x,
photo-2x.jpg 2x,
photo-3x.jpg 3x"
alt="A landscape">
Here's what this means:
photo.jpg 1x— standard resolution (1 CSS pixel = 1 device pixel)photo-2x.jpg 2x— double resolution for Retina/high-DPI screensphoto-3x.jpg 3x— triple resolution for ultra-high-DPI displays
The src attribute remains as a fallback for older browsers that don't understand srcset.
How the Browser Decides
The browser looks at the device's pixel density and selects the closest match. A standard monitor chooses 1x, a Retina MacBook chooses 2x, and some high-end phones might choose 3x.
Key Takeaway: The srcset attribute with x descriptors lets you provide multiple image resolutions so browsers can deliver sharp images to high-DPI screens while saving bandwidth for standard displays.