Lesson 3 of 7
Responsive Images & Optimization
Learn to serve the right image for every device and screen size. Master the srcset attribute, sizes attribute, art direction with the picture element, and image optimization techniques that directly impact Core Web Vitals and page speed scores.
Why Responsive Images Matter
Serving a 2000px wide image to a mobile phone wastes bandwidth and slows page load. Google's Largest Contentful Paint (LCP) metric directly measures how fast your largest image loads - it's a Core Web Vital that affects search rankings. Responsive images solve this by letting browsers choose the best image for each device: smaller images for phones, larger for desktops, and WebP/AVIF for browsers that support them.
srcset serves resolution-optimized images tailored to each device screen
Image Optimization Best Practices
- Use WebP as primary format - 25-34% smaller than JPEG at the same quality. Fallback to JPEG with <picture>
- Compress images before uploading - tools like Squoosh.app, TinyPNG, or ImageMagick can reduce file size 50-80%
- Serve exact sizes - never scale a 2000px image down with CSS. Generate multiple sizes at build time
- Use loading='lazy' for below-fold images - saves bandwidth and improves initial load time
- Always set width and height attributes - prevents layout shifts (CLS) when images load
- Use CDN with automatic format conversion - Cloudinary, imgix, and Vercel Image Optimization serve the best format automatically
Responsive Images Code
<!-- srcset with width descriptors (w) -->
<img
src="product-800.jpg"
srcset="product-400.jpg 400w,
product-800.jpg 800w,
product-1200.jpg 1200w,
product-1600.jpg 1600w"
sizes="(max-width: 480px) 100vw,
(max-width: 768px) 50vw,
33vw"
alt="Red sneakers product photo"
width="800"
height="600"
loading="lazy"
>
<!-- Art direction: different crops for mobile vs desktop -->
<picture>
<source
media="(max-width: 600px)"
srcset="hero-mobile.jpg"
>
<source
media="(max-width: 1200px)"
srcset="hero-tablet.jpg"
>
<img src="hero-desktop.jpg" alt="Company team at annual meetup">
</picture>
<!-- Format + resolution fallback -->
<picture>
<source type="image/avif" srcset="photo-400.avif 400w, photo-800.avif 800w">
<source type="image/webp" srcset="photo-400.webp 400w, photo-800.webp 800w">
<img src="photo-800.jpg" alt="Landscape photo" loading="lazy" width="800" height="600">
</picture>Quick Quiz: Responsive Images
Key Takeaways
- Learn to serve the right image for every device and screen size.
- Use WebP as primary format - 25-34% smaller than JPEG at the same quality. Fallback to JPEG with <picture>
- Compress images before uploading - tools like Squoosh.app, TinyPNG, or ImageMagick can reduce file size 50-80%
- Serve exact sizes - never scale a 2000px image down with CSS. Generate multiple sizes at build time
Finished this lesson?