Lesson 7 / 25
Images & pictures element
Make images responsive with max-width: 100%, use srcset for device-aware image loading, and leverage the <picture> element for art direction.
Basic responsive images
A single line of CSS makes images responsive: img { max-width: 100%; height: auto; } — the image scales to fit its container but never exceeds its natural size.
srcset for resolution-aware images
Serve different image sizes based on screen density (1x, 2x) or viewport width to save bandwidth on mobile.
<!-- Serve appropriate size based on device -->
<img
src="hero-600w.jpg"
srcset="hero-400w.jpg 400w, hero-800w.jpg 800w, hero-1200w.jpg 1200w"
sizes="(max-width: 600px) 400px, (max-width: 1200px) 800px, 1200px"
alt="Hero image"
>Art direction with picture element
Use
<picture>
<!-- Mobile: tall portrait crop -->
<source media="(max-width: 600px)" srcset="hero-portrait.jpg">
<!-- Tablet: wider crop -->
<source media="(max-width: 1200px)" srcset="hero-landscape.jpg">
<!-- Desktop: full image -->
<img src="hero-fullwidth.jpg" alt="Hero">
</picture>Lazy loading and aspect ratio
Use loading="lazy" to defer image loading. Use CSS aspect-ratio property to reserve space before images load, preventing layout shift.