srcset provides multiple image sources for different resolutions or sizes. Combined with sizes, it lets the browser choose the best image for the device and viewport. This impacts performance and data usage, so test the chosen image under throttled network.
What is the purpose of the srcset attribute in the <img> tag?
Use guided tracks for structured prep, then practice company-specific question sets when you want targeted interview coverage.
Overview
The srcset attribute provides a list of image sources with different sizes or resolutions. The browser picks the most suitable one based on device pixel density (DPR) and layout width.
Term | Meaning |
|---|---|
| Specify image density for standard or Retina screens. |
| Specifies the image’s intrinsic width for responsive design. |
| Tells the browser how much space the image will occupy. |
Example: Resolution Switching
<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
<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
srcfallback.
Higher-res images improve quality but cost bandwidth. Test on throttled network and inspect the chosen resource in DevTools.
Think of srcset as giving the browser a menu of images — it chooses the one that fits best on the user’s device.
srcsetenables responsive and high-resolution images.- Improves load time by avoiding unnecessary large images.
- Crucial for performance and responsive design.
<li>Used together with sizes for adaptive layouts.