Responsive Images with srcset and DPR

Serve resolution-appropriate images using the HTML srcset attribute with pixel density descriptors. Combine with sizes for viewport-based responsive image loading.

Practical

Detailed Explanation

Responsive Images and Device Pixel Ratio

Serving the correct image resolution for each device's DPR prevents blurry images on Retina screens and avoids wasting bandwidth on standard displays.

DPR-Based srcset

<img
  src="photo-400.jpg"
  srcset="
    photo-400.jpg 1x,
    photo-800.jpg 2x,
    photo-1200.jpg 3x
  "
  alt="Product photo"
  width="400"
  height="300"
/>

The browser selects the image matching the device's DPR:

  • DPR 1: loads photo-400.jpg (400px wide)
  • DPR 2: loads photo-800.jpg (800px wide, displayed at 400 CSS pixels)
  • DPR 3: loads photo-1200.jpg (1200px wide)

Width-Based srcset with sizes

For images that change size based on viewport width:

<img
  srcset="
    photo-320.jpg 320w,
    photo-640.jpg 640w,
    photo-960.jpg 960w,
    photo-1280.jpg 1280w
  "
  sizes="
    (max-width: 640px) 100vw,
    (max-width: 1024px) 50vw,
    33vw
  "
  src="photo-640.jpg"
  alt="Responsive photo"
/>

The browser calculates the optimal image:

  1. Determines the display size from sizes (e.g., 50vw on a 1024px viewport = 512px)
  2. Multiplies by DPR (512 × 2 = 1024px for Retina)
  3. Picks the closest srcset candidate (photo-960.jpg)

The picture Element

For art direction (different crops at different sizes):

<picture>
  <source media="(min-width: 1024px)" srcset="hero-wide.jpg" />
  <source media="(min-width: 640px)" srcset="hero-medium.jpg" />
  <img src="hero-mobile.jpg" alt="Hero image" />
</picture>

CSS Background Images

.hero {
  background-image: url('bg-1x.jpg');
}

@media (min-resolution: 2dppx) {
  .hero {
    background-image: url('bg-2x.jpg');
  }
}

Performance Tip

Use modern formats (WebP, AVIF) within srcset for significant file size savings while maintaining quality across all DPR values.

Use Case

Web developers building image-heavy pages (e-commerce, portfolios, media sites) need srcset and sizes to serve appropriately-sized images that look crisp on Retina displays without wasting bandwidth.

Try It — Screen Info Display

Open full tool