What are responsive images?

Responsive images are techniques that serve each device an image file sized and formatted appropriately for its screen, so phones do not download huge desktop images and high-density displays still look sharp. In HTML this is done with srcset, sizes, <picture>, and modern formats, plus CSS that lets the image scale fluidly.

The toolkit

  • Fluid CSS: img { max-width: 100%; height: auto; } so images shrink with their container.
  • Resolution switching: <img srcset="a-480.jpg 480w, a-960.jpg 960w" sizes="(max-width: 600px) 100vw, 50vw">; the browser picks the smallest adequate file.
  • Density switching for fixed-size images: srcset="logo.png 1x, logo@2x.png 2x".
  • Art direction and formats: <picture> with <source media> and <source type="image/avif">.
  • Prevent layout shift: always set width and height (the browser derives the aspect ratio).
  • Loading strategy: loading="lazy" below the fold, fetchpriority="high" for the LCP image.

Why it matters

Images are often the largest bytes on a page. Serving a 2400px JPEG to a 375px phone wastes data and slows Largest Contentful Paint.

Generating the variants

Image CDNs (Cloudinary, imgix) and frameworks (Next.js <Image>, Astro <Image>) create the different sizes and formats automatically from one source image.

Interview tip

Explain that sizes tells the browser how wide the image will display before CSS loads, which is why it is needed for w descriptors.

Code example

html
1<style>
2 body { font-family: system-ui; }
3 .grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(240px, 1fr)); gap: 12px; }
4 img { width: 100%; height: auto; border-radius: 8px; display: block; }
5</style>
6<div class="grid">
7 <img
8 src="https://picsum.photos/id/1043/800/500"
9 srcset="https://picsum.photos/id/1043/400/250 400w,
10 https://picsum.photos/id/1043/800/500 800w,
11 https://picsum.photos/id/1043/1600/1000 1600w"
12 sizes="(max-width: 520px) 100vw, 50vw"
13 width="800" height="500"
14 alt="Sunset over a coastal town"
15 loading="lazy" decoding="async">
16 <img
17 src="https://picsum.photos/id/1050/800/500"
18 srcset="https://picsum.photos/id/1050/400/250 400w,
19 https://picsum.photos/id/1050/800/500 800w,
20 https://picsum.photos/id/1050/1600/1000 1600w"
21 sizes="(max-width: 520px) 100vw, 50vw"
22 width="800" height="500"
23 alt="Waves breaking on rocks"
24 loading="lazy" decoding="async">
25</div>
26<p id="out"></p>
27<script>
28 addEventListener("load", () => {
29 document.getElementById("out").textContent =
30 `DPR ${devicePixelRatio}: loaded ` + [...document.images].map((i) => i.currentSrc.split("/").slice(-2).join("/")).join(", ");
31 });
32</script>

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the HTML & CSS set.

Open in study app