Images, video and embeds
Media makes pages engaging, but it's also usually the heaviest part of a page. Pros serve the right file to each device and keep pages fast.
Responsive images with srcset
Why send a 2000px-wide photo to a 400px phone screen? srcset lists several sizes, sizes says how wide the image will be displayed, and the browser picks the best file.
<img
src="photo-800.jpg"
srcset="photo-400.jpg 400w, photo-800.jpg 800w, photo-1600.jpg 1600w"
sizes="(max-width: 600px) 100vw, 50vw"
alt="Sunset over Malpe beach"
width="800" height="533"
loading="lazy"
decoding="async"
>400wmeans "this file is 400 pixels wide".sizessays: on screens up to 600px the image fills the viewport width; otherwise it takes half.loading="lazy"delays off-screen images until the user scrolls near them. Don't lazy-load the main image at the top of the page.
<picture>: art direction and modern formats
Use <picture> to:
- Serve AVIF/WebP with a JPEG fallback, often 30–50% smaller.
- Art-direct: show a different crop on mobile.
SVG: perfect icons and logos
SVG is vector graphics written as markup. It stays sharp at any size, it's tiny, and you can style it with CSS.
Try changing the colours or making the smile bigger.
Video
| Attribute | Effect |
|---|---|
controls |
Show play, pause and volume controls |
poster |
Image shown before playing |
preload="metadata" |
Load only duration and size, not the whole file |
autoplay muted loop playsinline |
Background-style video (browsers only allow autoplay when muted) |
<track kind="captions"> |
Captions in WebVTT format, essential for accessibility |
Audio
Embedding other sites: <iframe>
YouTube videos, Google Maps and CodePens are all embedded with iframes.
<iframe
width="560" height="315"
src="https://www.youtube-nocookie.com/embed/VIDEO_ID"
title="Intro to Docker (video)"
loading="lazy"
allow="accelerometer; encrypted-media; picture-in-picture"
allowfullscreen>
</iframe>- Always give iframes a
titlefor screen readers. - Use
loading="lazy", because embeds are heavy. - Use the
sandboxattribute to restrict untrusted content. The live previews on this site use a sandboxed iframe!
Practice
Build a "product showcase": a responsive <picture> of the product, an inline SVG "verified" badge icon, and a <video> with a poster and controls. Give every element appropriate accessibility attributes.
1.What does loading="lazy" do on an image?
2.Why provide a <track kind="captions"> for video?