Section 27: Responsive Images — Picture, Srcset and Sizes
Learning Objectives
- Understand why responsive images matter.
- Use srcset and sizes to offer different image resolutions.
- Use picture and source for art direction and alternate formats.
- Understand image dimensions and accessibility.
1. What Are Responsive Images?
Responsive images let the browser choose an appropriate image resource based on the display size, layout and device capabilities. This can improve image quality and reduce unnecessary downloads.
2. Basic Image
<img
src="/images/course-banner-800.jpg"
alt="HTML course banner"
width="800"
height="450">Width and height communicate the image's intrinsic dimensions and help browsers reserve layout space. CSS can still scale the image to fit its container.
3. Using srcset with Width Descriptors
<img
src="/images/course-800.jpg"
srcset="/images/course-400.jpg 400w,
/images/course-800.jpg 800w,
/images/course-1200.jpg 1200w"
sizes="(max-width: 600px) 100vw, 800px"
width="800"
height="450"
alt="Students learning HTML on a laptop">The w descriptors identify the intrinsic pixel widths of the image resources. The sizes attribute describes the image's expected rendered width at different viewport sizes. The browser uses these hints along with display density and other factors to select a suitable resource.
4. Using Density Descriptors
<img
src="/images/logo.png"
srcset="/images/logo.png 1x,
/images/logo-2x.png 2x"
width="200"
height="60"
alt="Codementrix">Density descriptors such as 1x and 2x are an alternative to width descriptors. Do not mix width descriptors and pixel-density descriptors in the same srcset list.
5. Art Direction with picture
Use picture when different layouts need different crops or compositions, such as a wide desktop banner and a portrait mobile image.
<picture>
<source
media="(max-width: 600px)"
srcset="/images/banner-mobile.jpg">
<source
media="(min-width: 601px)"
srcset="/images/banner-desktop.jpg">
<img
src="/images/banner-desktop.jpg"
width="1200"
height="500"
alt="A developer working on a web project">
</picture>The browser checks source elements in order and uses a suitable match. The img element remains necessary as the fallback and carries the alternative text.
6. Alternate Image Formats
<picture>
<source type="image/avif" srcset="/images/course.avif">
<source type="image/webp" srcset="/images/course.webp">
<img src="/images/course.jpg"
width="800" height="450"
alt="HTML course preview">
</picture>This lets supporting browsers use AVIF or WebP while retaining a JPEG fallback. The image files must actually exist and be served with appropriate media types.
7. Responsive Image CSS
<style>
img {
max-width: 100%;
height: auto;
}
</style>This common rule prevents images from overflowing their containers while preserving their aspect ratio when dimensions are not otherwise constrained.