Srcset and sizes
Use srcset and sizes for different screen sizes.
What is srcset?
Sending the same large image to every screen is both slow and a waste of data. The srcset attribute offers the browser several resolutions of the image; the browser picks one based on the device.
The shape is: <img src="forest-s.jpg" srcset="forest-s.jpg 480w, forest-m.jpg 800w, forest-l.jpg 1200w" alt="...">. The w suffix states the image's real width in pixels.
The sizes attribute
The sizes attribute tells how much screen width the image will take. The browser then picks from srcset accordingly.
Example: sizes="(max-width: 600px) 100vw, 50vw". This says on screens narrower than 600 pixels the image spans the full width, and half the width on wider screens. vw is one percent of the viewport.
Exercise Write a responsive hero image
Add a single <img> inside body. It should hold: src (e.g. /images/forest.jpg), srcset (at least two file widthw entries), sizes (with a media condition, e.g. (max-width: 600px) 100vw, 50vw) and a non-empty alt.
Show example solution
<body>
<img src="/images/forest.jpg"
srcset="/images/forest-s.jpg 480w,
/images/forest-m.jpg 800w,
/images/forest-l.jpg 1200w"
sizes="(max-width: 600px) 100vw, 50vw"
alt="Forest view">
</body>
Test yourself
-
Which srcset syntax is correct?
- srcset="small.jpg 480w, medium.jpg 800w"
- srcset="small.jpg, medium.jpg, large.jpg"
- srcset="480w small.jpg, 800w medium.jpg"
- srcset="small.jpg; medium.jpg; large.jpg"
Show answer
srcset="small.jpg 480w, medium.jpg 800w" — Correct. Each entry follows the 'file widthw' shape.
-
Complete the sizes value
<img src="/images/forest.jpg" srcset="/images/forest-s.jpg 480w, /images/forest-l.jpg 1200w" ____ alt="Forest">Show answer
<img src="/images/forest.jpg" srcset="/images/forest-s.jpg 480w, /images/forest-l.jpg 1200w" sizes="(max-width: 600px) 100vw, 50vw" alt="Forest"> -
Match each term to its meaning
- srcset
- Resolution candidates
- sizes
- Visible width
- w
- Pixel width
- vw
- Viewport percent
-
How does the browser pick an image from srcset?
- It picks the smallest file
- It picks the largest file
- It loads every file in order
- It picks the best match using sizes and the device
Show answer
It picks the best match using sizes and the device — Correct. The browser looks at the sizes value and the device's pixel density.