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

LowIntermediateHtml
Preparing for interviews?

Use guided tracks for structured prep, then practice company-specific question sets when you want targeted interview coverage.

Quick Answer

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.

Answer

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

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
24 / 27