Sub topic 1
Why one image file is not enough
Prerequisites
You should know basic HTML, including img, src, and alt. You should also understand CSS media queries, viewport units, common image formats, and the difference between CSS pixels and device pixels.
Why one image file is not enough
A single large image can look sharp on every screen, but it wastes bandwidth on small devices. A single small image loads quickly, but it can look blurry on a high-density display. Responsive images let the browser choose a suitable file from several candidates.
The browser considers the image's rendered width, the device pixel ratio, and the available candidates.
The img element as the baseline and fallback
Start with a normal img element. Its src is the fallback URL, and alt describes the image for people who cannot see it.
<img
src="photo-800.jpg"
width="800"
height="600"
alt="A lighthouse on a rocky coast at sunset">The width and height attributes also describe the aspect ratio. Browsers can reserve that space before the image loads, reducing layout shift.
Serving sharper images with x descriptors
Use density descriptors when the image has a fixed display size. The 1x candidate targets a normal-density screen, while 2x targets a screen that needs twice as many source pixels.
<img
src="photo-400.jpg"
srcset="photo-400.jpg 1x, photo-800.jpg 2x"
width="400"
height="300"
alt="A lighthouse on a rocky coast at sunset">The browser can select based on device pixel ratio and may also account for network conditions.
Describing candidates with w descriptors
For fluid images, use width descriptors. Each w value gives the image's intrinsic width.
<img
src="photo-800.jpg"
srcset="photo-400.jpg 400w, photo-800.jpg 800w, photo-1600.jpg 1600w"
sizes="100vw"
width="1600"
height="1200"
alt="A lighthouse on a rocky coast at sunset">Telling the browser how wide the image will be with sizes
sizes describes the image's expected CSS width before layout completes. The browser combines that width with device pixel ratio, then selects a suitable srcset candidate. If the image occupies half the viewport on medium screens, describe that directly:
sizes="(min-width: 40em) 50vw, 100vw"An incorrect sizes value can cause an unnecessarily large or blurry download.
Exercise
Which descriptor fits a fluid image that is full width on small screens and half width on larger screens?
Show answer
Use width descriptors such as 400w and 800w, with sizes="(min-width: 40em) 50vw, 100vw".