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
<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"
>400wmeans "this image is 400 pixels wide"sizestells the browser how wide the image will be displayed- The browser picks the best image based on viewport and pixel density
Pixel Density Descriptors
<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
<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
<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:
<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"
>| Viewport | Image display width |
|---|---|
| ≤ 480px | 100% of viewport |
| ≤ 960px | 50% of viewport |
| > 960px | 33% of viewport |
CSS Object-fit for Responsive Images
.responsive-img {
width: 100%;
height: 300px;
object-fit: cover; /* Fills area, may crop */
object-position: center;
}Loading Optimization
<!-- 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 readyA concise answer to help you respond confidently on this topic during an interview.