HTML & CSSMedium
What is srcset?
srcset is an attribute on <img> and <source> that lists several candidate files for the same image so the browser can pick the best one for the device's viewport width and pixel density. It comes in two forms: width descriptors (480w), used together with sizes, and density descriptors (2x).
Width descriptors (w) + sizes
srcset="card-400.jpg 400w, card-800.jpg 800w, card-1200.jpg 1200w"
sizes="(max-width: 600px) 100vw, 33vw"
wis the file's real pixel width.sizesdescribes how wide the image will be displayed at different breakpoints. The browser multiplies that by the device pixel ratio and picks the smallest file that is large enough.- Without
sizes, the browser assumes100vw, often downloading too large a file. sizes="auto"(withloading="lazy") lets supporting browsers use the real layout width.
Density descriptors (x)
srcset="logo.png 1x, logo@2x.png 2x, logo@3x.png 3x"
Best for images with a fixed CSS size, such as logos and avatars.
Behavior details
- The choice is a hint: browsers may pick a smaller file on slow connections or reuse a larger one already cached.
srcremains the fallback for very old browsers.- Check the result with
img.currentSrc. - You cannot mix
wandxdescriptors in onesrcset.
Interview tip
Being able to explain how sizes and DPR combine to choose a file is what separates a solid answer from a vague one.
Code example
html
1<style>2 body { font-family: system-ui; }3 .avatar { width: 64px; height: 64px; border-radius: 50%; }4 .hero { width: 100%; max-width: 720px; height: auto; border-radius: 8px; }5</style>67<!-- Fixed display size: density descriptors -->8<img class="avatar" alt="Avatar of Ada"9 src="https://picsum.photos/id/64/64/64"10 srcset="https://picsum.photos/id/64/64/64 1x,11 https://picsum.photos/id/64/128/128 2x,12 https://picsum.photos/id/64/192/192 3x">1314<!-- Fluid size: width descriptors + sizes -->15<img class="hero" alt="City skyline at night" width="1200" height="600"16 src="https://picsum.photos/id/1067/800/400"17 srcset="https://picsum.photos/id/1067/480/240 480w,18 https://picsum.photos/id/1067/800/400 800w,19 https://picsum.photos/id/1067/1200/600 1200w"20 sizes="(max-width: 760px) 100vw, 720px">2122<pre id="out"></pre>23<script>24 addEventListener("load", () => {25 document.getElementById("out").textContent = [...document.images]26 .map((i) => `${i.alt}: ${i.currentSrc} (DPR ${devicePixelRatio})`).join("\n");27 });28</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.