What is the purpose of the srcset attribute in the <img> tag?

HighIntermediateHtml
Quick Answer

The srcset attribute gives the browser multiple image candidates so it can pick the right file for DPR and layout width. The production pitfall is shipping large images or mismatched sizes, which wastes bandwidth and makes responsive image debugging harder.

Answer

Overview

The srcset attribute gives the browser a set of image candidates so it can choose based on device pixel ratio and layout width. Under the hood, this is a performance feature, not just a syntax trick. The common pitfall is providing srcset without accurate sizes or asset widths, which causes blurry images, oversized downloads, or confusing network debugging.

Term

Meaning

1x, 2x

Specify image density for standard or Retina screens.

w descriptor

Specifies the image’s intrinsic width for responsive design.

sizes

Tells the browser how much space the image will occupy.

Key components of responsive image loading

Example: Resolution Switching

HTML
<img src="image-1x.jpg" 
     srcset="image-1x.jpg 1x, image-2x.jpg 2x" 
     alt="Mountain landscape">
                  

High-density screens automatically load image-2x.jpg, while standard screens use image-1x.jpg.

Example: Responsive Widths

HTML
<img src="small.jpg"
     srcset="small.jpg 480w, medium.jpg 800w, large.jpg 1200w"
     sizes="(max-width: 600px) 480px, (max-width: 1000px) 800px, 1200px"
     alt="Sunset over the city">
                  

The browser calculates which image fits best based on current viewport width — no JavaScript needed.

Practical scenario
A product card needs responsive images for mobile, tablet, and desktop, so you use srcset and sizes to match device width.

Common pitfalls

  • Omitting sizes, which makes the browser guess and over-download.
  • Using the wrong descriptors (w vs x), leading to blurry or heavy images.
  • Not providing a reasonable src fallback.
Trade-off or test tip
Higher-res images improve quality but cost bandwidth. Test on throttled network and inspect the chosen resource in DevTools.

Still so complicated?

Think of srcset as giving the browser a menu of images — it chooses the one that fits best on the user’s device.

Summary
  • srcset enables responsive and high-resolution images.
  • Improves load time by avoiding unnecessary large images.
  • <li>Used together with sizes for adaptive layouts.
  • Crucial for performance and responsive design.
Similar questions
Guides
Preparing for interviews?

Use the relevant interview-question hub first, then move into a concrete study plan before targeted company sets.