Lesson 4 of 52HTML
Images and Media
Add images, video and audio that load fast and work for everyone: alt text, formats, lazy loading, srcset, picture, figure and captions.
Images make a page feel alive, but they are also the heaviest part of most websites and a common accessibility gap. A single oversized photo can make a page slow on a phone, and an image with no description is a blank space to anyone who cannot see it. This lesson covers how to add images properly: describing them with alt text, reserving their space so the page does not jump, choosing a file format, and letting the browser pick the right size. Then you will add captions, video and audio.
The img element
An image is a void element (no closing tag) with two essential attributes:
<img src="images/pancakes.jpg" alt="A stack of pancakes topped with blueberries and syrup">src(source) is the path to the image file. It follows the same rules as link paths: relative likeimages/pancakes.jpg, or absolute likehttps://example.com/pancakes.jpg.alt(alternative text) describes the image in words. Screen readers read it aloud, search engines index it, and the browser shows it if the image fails to load.
You can see that last behaviour here. The file pancakes.jpg does not exist in this preview, so the browser falls back to the alt text:
Preview
Try deleting the whole alt attribute: now there is only a tiny broken icon (or nothing at all), and a screen reader might read out the file name instead. Put it back and try rewriting the alt text to be shorter.
Writing good alt text
Alt text should give someone who cannot see the image the same useful information a sighted person gets from it. Ask yourself: "If I were reading this page aloud to a friend on the phone, what would I say about this image?"
- Be specific and short. "Golden retriever catching a frisbee on a beach" beats "dog" and beats a 60-word essay. One sentence is usually plenty.
- Skip "image of" or "picture of". Screen readers already announce that it is an image.
- Match the purpose. On a shop page, "Red leather boots with a block heel, side view" helps a buyer. On a blog post about a trip, "Our tent at sunrise, with mist over the lake" sets the scene.
- Images that are links or buttons describe the action. A magnifying glass icon inside a search link should have the alt "Search", not "Magnifying glass".
- Decorative images get an empty alt. A purely decorative swirl or background texture adds nothing for a listener, so write
alt="". The empty value tells screen readers to skip it entirely. Leavingaltout altogether is different and worse: the screen reader may read the file name, like "swirl-final-v2 dot png". - Text in images should be repeated in the alt. If a banner says "50% off this weekend", the alt says it too.
Reserve the space with width and height
Images load after the HTML. If the browser does not know how big an image will be, it gives it zero space at first, then shoves the content below it down when the image arrives. You have probably felt this: you go to tap a link and the page jumps, so you tap an advert instead. This is called layout shift, and Google measures it as CLS (Cumulative Layout Shift), one of its Core Web Vitals.
The fix is simple. Add the image's real width and height in pixels:
<img src="pancakes.jpg" alt="..." width="1200" height="800">Modern browsers use those two numbers to work out the image's aspect ratio (its shape, here 3 to 2) and reserve the right amount of space before the file arrives. You can still resize the image with CSS: a common rule is max-width: 100%; height: auto;, which keeps it inside its container and keeps the shape.
The preview below cannot download photos from the internet, so its image is a tiny drawing written straight into the src as a data URL (the file's contents as text). On your own site, src would simply be a file path.
Preview
Change width="300" to width="150", and notice the height scales too because of height: auto in the CSS. Then make the preview narrower (on a phone it already is) and watch max-width: 100% keep the image inside the page.
Choosing a file format
| Format | Best for | Notes |
|---|---|---|
JPEG (.jpg) | Photos | Small files, lossy (throws away detail you rarely notice). No transparency. |
PNG (.png) | Screenshots, graphics with sharp edges, transparency | Lossless, so photos come out large. |
SVG (.svg) | Logos, icons, simple illustrations | A vector format: shapes described as code, sharp at any size and usually tiny. |
WebP (.webp) | Photos and graphics | Typically noticeably smaller than JPEG or PNG at similar quality. Supported in all modern browsers. |
AVIF (.avif) | Photos | Often smaller still than WebP. Supported in current versions of all major browsers; check Can I Use if you must support older ones. |
A quick rule: SVG for logos and icons, WebP or AVIF for photos (with a JPEG fallback if needed), PNG for screenshots. Also resize before you upload. A photo straight off a phone can be 4000 pixels wide and several megabytes, when the page only ever shows it 800 pixels wide.
Match each image to a sensible format.
Lazy loading
By default the browser downloads every image on the page straight away, even ones far down that the visitor may never scroll to. Add loading="lazy" and the browser waits until the image is close to coming into view:
<img src="gallery-12.jpg" alt="..." width="800" height="600" loading="lazy">This is supported in all modern browsers and can save a lot of data on long pages. One important exception: do not lazy-load the big image at the top of the page. The main hero image is often the largest thing on screen, and Google measures how fast it appears (LCP, Largest Contentful Paint). Delaying it makes the page feel slower. Lazy-load the images below the fold (below the first screenful), not the first one people see.
loading="lazy"?Responsive images: srcset and picture
A phone with a small screen does not need the same giant image as a wide desktop monitor. The srcset attribute lets you offer several sizes of the same image and lets the browser choose:
<img
src="cake-800.jpg"
srcset="cake-400.jpg 400w, cake-800.jpg 800w, cake-1600.jpg 1600w"
sizes="(max-width: 600px) 100vw, 600px"
alt="A slice of lemon drizzle cake on a blue plate"
width="800" height="533">srcsetlists each file with its real width, followed byw.sizestells the browser how wide the image will be shown: the full viewport width (100vw) on screens up to 600 pixels wide, otherwise 600 pixels.srcis the fallback for browsers that ignoresrcset.
The browser combines these with the screen's size and pixel density and downloads just one file. You will revisit this in the responsive design lesson; for now, knowing it exists is enough.
When you want to offer different formats, use the picture element. It holds one or more source elements and a normal img at the end:
<picture>
<source srcset="cake.avif" type="image/avif">
<source srcset="cake.webp" type="image/webp">
<img src="cake.jpg" alt="A slice of lemon drizzle cake" width="800" height="533">
</picture>The browser checks the first source. If it supports AVIF, it uses this file and stops looking.
picture element, where does the alt text go?Checking which file the browser chose
srcset fails silently. A wrong sizes does not break anything you can see: the image looks fine, it is just three times heavier than it should be. So after writing one, check what actually downloaded. The selection maths (slot width times pixel density, then the smallest candidate that covers it) is covered in Loading Fonts and Images Fast. This section is about seeing the result.
The browser picks one candidate using three inputs: the slot width from sizes, the screen's device pixel ratio (DPR: 1 on most office monitors, 2 or 3 on phones and laptops with dense screens), and anything already in its cache. The preview below builds four candidate files labelled with their width. Change the sizes value and read which one loaded. The image's CSS width follows your choice, so sizes always tells the truth here:
Preview
With 100vw, the image fills the whole preview, so the browser takes a large file. With 150px, a 1x screen needs only the 200w file, and a 2x screen needs 300 pixels, so it takes the 400w file. Now imagine the CSS says 150px but you forgot sizes: the browser would still take the 100vw choice. The image on screen may look identical either way: that is exactly why this bug survives code review.
On a real site, check it in DevTools:
- Open the Network panel, tick Disable cache, filter by Img, and reload. Each
imgshould appear once, with a file name that matches its displayed size. Two downloads of the same picture at different widths means the browser picked once, then picked again after something changed. - In the Elements panel, hover the
imgtag'ssrc. Chrome shows the rendered size, the intrinsic size of the file, and the current source, which is the candidate it chose. - In the Console, select the element and run
$0.currentSrc. That is the URL actually in use, whateversrcsays. - Use the device toolbar to test a phone width at DPR 3 and a desktop width at DPR 1. A layout that is right on both is usually right everywhere.
Two behaviours confuse people the first time. Browsers are allowed to keep using a larger file they already have, so after you narrow the window you often still see the big one; reload with the cache disabled to see a fresh choice. And resizing a desktop window is not the same test as loading the page fresh on a phone, because what is already loaded and cached affects what the browser picks next.
$0.currentSrc ends in card-1600.webp. The img has srcset with 400w, 800w and 1600w files and no sizes. What is the cause?Captions with figure and figcaption
When an image (or a chart, code sample or quote) comes with a visible caption, wrap them together in figure and put the caption in figcaption. This tells browsers and screen readers that the caption belongs to that image.
Preview
Change the caption text, then try moving the figcaption above the img. Both positions are allowed: the caption can be the first or the last child of the figure. Notice the caption and alt say different things. The alt describes what the image shows; the caption adds information everyone sees.
Video and audio
The video and audio elements play media without any plugin. Always add the controls attribute so people get play, pause and volume buttons:
<video controls width="640" height="360" poster="intro-poster.jpg">
<source src="intro.webm" type="video/webm">
<source src="intro.mp4" type="video/mp4">
<track kind="captions" src="intro-en.vtt" srclang="en" label="English">
Your browser cannot play this video. <a href="intro.mp4">Download it</a> instead.
</video>
<audio controls src="episode-1.mp3"></audio>sourceelements work like they do inpicture: the browser plays the first format it supports. MP4 (H.264) plays almost everywhere.posteris an image shown before the video starts.trackadds captions from a WebVTT (.vtt) text file. Captions help deaf viewers, people watching with the sound off, and people learning the language.- The text inside shows only in browsers that cannot play video at all.
Browsers block videos from playing sound on their own. If you use autoplay (for a silent background clip, say), you must also add muted, and you should give people a way to pause it. For long videos, many sites host them on a video platform and embed the player, because serving large video files yourself costs bandwidth.
Captions, transcripts and audio description
Video is where accessibility audits find the most expensive problems, because fixing them means producing new content, not changing a tag. WCAG asks for different things depending on the media:
| Media | What WCAG asks (level) | Who it is for |
|---|---|---|
| Prerecorded video with sound | Captions (1.2.2, A) | Deaf and hard of hearing viewers, anyone with the sound off |
| Live video with sound | Captions (1.2.4, AA) | The same, in real time |
| Audio only, like a podcast | A text transcript (1.2.1, A) | Anyone who cannot hear it |
| Video where the picture carries information | Audio description (1.2.5, AA) | Blind and low-vision viewers |
Captions are not subtitles. Subtitles (kind="subtitles") translate the dialogue for people who can hear but do not speak the language. Captions (kind="captions") assume the viewer cannot hear at all, so they also name speakers and include meaningful sounds: "[oven timer beeps]", "[laughter]". Captions are written in WebVTT, a plain text format of timed cues:
WEBVTT
00:00:00.000 --> 00:00:03.500
<v Priya>Welcome to Crumb Club.
00:00:03.500 --> 00:00:06.000
[oven timer beeps]
00:00:06.000 --> 00:00:10.000
<v Priya>That means the starter is ready.Each track element points at one file. Add default to the one that should be on when captions are switched on, and one track per language:
<video controls crossorigin="anonymous" width="640" height="360" poster="intro-poster.jpg">
<source src="https://media.crumbclub.example/intro.mp4" type="video/mp4">
<track kind="captions" src="https://media.crumbclub.example/intro-en.vtt" srclang="en" label="English" default>
<track kind="subtitles" src="https://media.crumbclub.example/intro-fr.vtt" srclang="fr" label="Français">
</video>Three details that catch teams in production. The server must send .vtt files as text/vtt, or some browsers ignore them. A track on another origin (a media CDN, say) needs CORS headers on that server and the crossorigin attribute on the video, otherwise the track silently fails to load. And auto-generated captions are a first draft: they get names, product terms and numbers wrong, so a person should correct them before they count.
Audio description is narration of what is shown but not said: "She folds the dough into thirds." The HTML spec has kind="descriptions", but browsers do not read those tracks aloud on their own, so in practice teams do one of two things. The cheap one is to write the script so the speaker describes what they are doing ("I am adding 100 grams of flour"), which needs no extra track. The other is a second version of the video with a described soundtrack, linked next to the player. A full text transcript beside the video, with the descriptions included, helps everyone and gives search engines text to index.
Autoplay, motion and background video
Browsers decide whether a video may start on its own. Chrome, Safari and Firefox all allow autoplay when the video is muted, and block or limit autoplay with sound until the person has interacted with the site. So a hero video needs autoplay muted loop playsinline. The playsinline attribute stops iPhones from jumping into full screen.
Being allowed to autoplay is not the same as being allowed by WCAG:
- 1.4.2 Audio Control (A): any sound that plays automatically for more than 3 seconds needs a way to pause it or turn it down, separate from the system volume. Simplest answer: never autoplay sound.
- 2.2.2 Pause, Stop, Hide (A): anything moving that starts automatically, lasts more than 5 seconds and sits alongside other content needs a way to pause it. A looping background video needs a visible pause button.
- Reduced motion: people who set "reduce motion" in their system settings (you met
prefers-reduced-motionin Transitions and Animations) should get the poster image instead of the motion. CSS cannot stop a video, so check the preference in script and only start playback when motion is allowed.
<div class="hero">
<video id="bg" muted loop playsinline preload="none" poster="hero-poster.jpg" aria-hidden="true">
<source src="hero.mp4" type="video/mp4">
</video>
<button id="toggle" type="button">Pause background video</button>
</div>
<script>
const video = document.getElementById("bg");
const button = document.getElementById("toggle");
const reduce = window.matchMedia("(prefers-reduced-motion: reduce)");
if (!reduce.matches) video.play();
button.hidden = reduce.matches;
button.addEventListener("click", () => {
if (video.paused) { video.play(); button.textContent = "Pause background video"; }
else { video.pause(); button.textContent = "Play background video"; }
});
</script>There is no autoplay attribute here on purpose: the script starts the video only when motion is allowed. aria-hidden="true" is fine because the video is decoration with no controls inside it, and preload="none" saves the download for anyone who never sees it play. Remember the poster image too. It is often the largest thing in the first screenful, so it can be the page's LCP element, and it deserves the same care over size and format as any hero image.
Embedding a hosted player
Most companies host long videos on YouTube, Vimeo or a video platform and embed the player in an iframe. Two things are easy to forget:
- Give every iframe a
title, such astitle="Video: shaping a sourdough loaf". A screen reader announces it when the user reaches the frame, and an untitled frame is a common audit finding. - The player is heavy. A typical embedded player loads a lot of JavaScript before anyone presses play. Add
loading="lazy"to iframes below the fold. For a player near the top, use a facade: show the thumbnail and a realbuttonlabelled "Play video: shaping a sourdough loaf", and only insert the iframe when it is pressed. Core Web Vitals and Page Speed shows how to measure the difference.
- alt text
- A text description of an image for screen readers, search engines, and when the image fails to load. Empty for decorative images.
- layout shift (CLS)
- Content jumping as late-loading things like images appear. Prevented by setting width and height.
- lazy loading
- loading="lazy": the browser waits to download an image until it is near the visible area.
- srcset
- An attribute listing several sizes of an image so the browser can download the best fit for the screen.
- picture
- An element that offers alternative image files, such as AVIF and WebP, with an img as the required fallback.
- figure / figcaption
- A self-contained image, chart or code sample together with its visible caption.
- SVG
- A vector image format that describes shapes as code, so it stays sharp at any size.
- device pixel ratio (DPR)
- How many physical screen pixels make up one CSS pixel. A 2x screen needs an image twice as wide to look sharp.
- WebVTT
- The plain text caption format (.vtt) loaded by the track element: timed cues, speaker tags and sound descriptions.
- captions vs subtitles
- Captions are for viewers who cannot hear and include speakers and sounds. Subtitles translate dialogue for viewers who can hear.
- facade
- A lightweight placeholder (thumbnail and play button) that loads a heavy embedded player only when pressed.