What is the srcset attribute?

HTML

The short answer

The srcset attribute on <img> elements lets you provide multiple image sources at different sizes or resolutions. The browser picks the best one based on the device's screen size and pixel density. This way, mobile users download a small image and desktop users with retina screens get a high-resolution one.

Basic usage — pixel density

<img
src="photo-400.jpg"
srcset="photo-400.jpg 1x, photo-800.jpg 2x"
alt="A photo"
/>

Regular screens load photo-400.jpg. Retina screens (2x pixel density) load photo-800.jpg. The src is the fallback for older browsers.

Width-based srcset

Tell the browser the actual width of each image file:

<img
src="photo-400.jpg"
srcset="
photo-400.jpg 400w,
photo-800.jpg 800w,
photo-1200.jpg 1200w
"
sizes="(max-width: 600px) 100vw, 50vw"
alt="A photo"
/>

The sizes attribute tells the browser how wide the image will be displayed:

  • On screens up to 600px wide: the image takes 100% of the viewport width
  • On larger screens: the image takes 50% of the viewport width

The browser uses this information plus the screen's pixel density to pick the best image file.

The picture element

For more control, use <picture> with different sources:

<picture>
<source
media="(min-width: 1024px)"
srcset="photo-desktop.jpg"
/>
<source
media="(min-width: 768px)"
srcset="photo-tablet.jpg"
/>
<img src="photo-mobile.jpg" alt="A photo" />
</picture>

This lets you serve completely different images (not just different sizes) based on the viewport.

Interview Tip

Show the basic srcset with pixel density descriptors (1x, 2x), then the width-based version with sizes. The key point is that the browser chooses the best image — you just provide the options. Mention <picture> for art direction (different crops for different screens).

Why interviewers ask this

This tests HTML knowledge and image optimization awareness. Serving the right image for the right device is a basic performance best practice that every frontend developer should know.