Skip to main content
Practice Problems

Responsive images: picture, srcset and sizes

Why Responsive Images?

Serving a single large image to all devices wastes bandwidth on mobile and looks poor on retina displays. Responsive images allow the browser to choose the best image based on screen size, resolution, and format support.


The srcset Attribute

srcset provides a list of image sources with their descriptors:

Width Descriptors

html
<img src="image-800.jpg" srcset=" image-400.jpg 400w, image-800.jpg 800w, image-1200.jpg 1200w " sizes="(max-width: 600px) 100vw, (max-width: 1000px) 50vw, 33vw" alt="Responsive image example" >
  • 400w means "this image is 400 pixels wide"
  • sizes tells the browser how wide the image will be displayed
  • The browser picks the best image based on viewport and pixel density

Pixel Density Descriptors

html
<img src="logo.png" srcset=" logo.png 1x, logo@2x.png 2x, logo@3x.png 3x " alt="Company logo" >

The picture Element

<picture> provides full control over which image to serve, including art direction and format selection:

Art Direction

html
<picture> <!-- Mobile: cropped portrait version --> <source media="(max-width: 600px)" srcset="hero-mobile.jpg"> <!-- Tablet: different crop --> <source media="(max-width: 1024px)" srcset="hero-tablet.jpg"> <!-- Desktop: full landscape --> <img src="hero-desktop.jpg" alt="Hero image"> </picture>

Format Selection

html
<picture> <source type="image/avif" srcset="photo.avif"> <source type="image/webp" srcset="photo.webp"> <img src="photo.jpg" alt="Photo in best available format"> </picture>

The browser picks the first supported format.

sizes Attribute

sizes describes how wide the image will be at different viewport widths:

html
<img srcset="img-300.jpg 300w, img-600.jpg 600w, img-900.jpg 900w" sizes=" (max-width: 480px) 100vw, (max-width: 960px) 50vw, 33vw " src="img-600.jpg" alt="Example" >
ViewportImage display width
≤ 480px100% of viewport
≤ 960px50% of viewport
> 960px33% of viewport

CSS Object-fit for Responsive Images

css
.responsive-img { width: 100%; height: 300px; object-fit: cover; /* Fills area, may crop */ object-position: center; }

Loading Optimization

html
<!-- Lazy loading (below the fold) --> <img src="photo.jpg" alt="..." loading="lazy"> <!-- Eager loading (above the fold, critical) --> <img src="hero.jpg" alt="..." loading="eager" fetchpriority="high"> <!-- Decode asynchronously --> <img src="photo.jpg" alt="..." decoding="async">

Important:

Always provide a fallback <img> inside <picture> and in the src attribute of srcset. Use loading="lazy" for images below the fold and serve modern formats (WebP, AVIF) with fallbacks for maximum performance.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.

Finished reading?
Practice Problems