Lesson 53 of 55 · HTML
Images
Duration: 9 min
Embedding Images (<img>)
<img src='images/photo.jpg' alt='Sunset over the mountains' width='600' height='400' loading='lazy' srcset='images/photo-600.jpg 600w, images/photo-1200.jpg 1200w' sizes='(max-width: 600px) 100vw, 600px' />
Essential attributes
src– Path to the image file.alt– Mandatory text for screen readers and when the image fails to load. Write concise, descriptive sentences.width/height– Reserve the exact space the image will occupy; this prevents layout shift (important for Core Web Vitals).loading='lazy'– Defers off‑screen images until they approach the viewport.srcsetandsizes– Serve responsive images for different viewport widths and pixel densities.
Optimization tips
- Compress images (ImageOptim, Squoosh) and serve modern formats (WebP, AVIF) when possible.
- Provide a low‑quality placeholder (blur‑up) or a tiny SVG LQIP to avoid a blank space during loading.
- Use
srcsetto offer 1× and 2× (or higher) variants for high‑DPI displays. - For decorative images, use an empty
alt=''to hide them from assistive technology.
Quick checklist for image accessibility
altattribute present and meaningful? ✅- Width & height defined to reserve space? ✅
loading='lazy'for non‑above‑the‑fold images? ✅srcset/sizesfor responsive delivery? ✅- Modern format (WebP/AVIF) provided? ✅
Tip: Run your page through Google Lighthouse → Performance → Avoid large layout shifts to confirm images are not causing CLS.
Try it yourself
Replace the src with a WebP version, add a srcset that includes a 2× image, and watch the network panel show the appropriate file being downloaded based on your screen’s pixel density.