005: Images and Media
Learning outcomes
By the end of this lesson, you can embed images with useful alternatives and intrinsic dimensions, distinguish informative from decorative images, associate captions with figures, add controllable audio/video with fallback content, and explain performance and accessibility costs of media.
Prerequisites and retrieval
Use the multi-page portfolio from 004. Trace the relative path from about.html to images/profile.webp. Recall that an image normally creates a separate HTTP request and that link text should communicate purpose.
Terminology
- Replaced element: An element whose rendered content is replaced by an external resource, such as img, video, audio. — Source: WHATWG: Embedded content
- Alternative text: The alt value supplying an equivalent purpose when an image cannot be perceived. — Source: WHATWG: Requirements for image alternatives
- Decorative image: An image conveying no information beyond surrounding text, correctly marked alt="". — Source: W3C WAI: Alt Decision Tree
- Intrinsic dimensions: A media resource’s natural pixel width and height before CSS resizing. — Source: MDN: HTML images
- Aspect ratio: The proportional relationship between width and height (width ÷ height). — Source: WHATWG: Dimension attributes
- Layout shift: Visible movement caused when content dimensions become known only after paint. — Source: MDN: HTML images
- Figure: A self-contained flow unit optionally captioned with figcaption, referenced as one unit. — Source: WHATWG: Grouping content — figure
- Controls: The boolean controls attribute exposes native play/pause/volume UI on media elements. — Source: WHATWG: Media elements — controls
- Poster: An image shown at the poster frame position while video data is unavailable. — Source: WHATWG: The video element — poster
- Captions: kind="captions" text tracks synchronizing speech and meaningful non-speech sound as text. — Source: W3C WAI: Audio and video media
- Functional image: "An image whose purpose is an action or destination (e.g., icon-only link). Its alt must convey that purpose." — Source: W3C WAI: Alt Decision Tree — Functional images
- Transcript: "A text equivalent of synchronized media, including dialogue, meaningful sounds, and visual information." — Source: W3C WAI: Audio and video media — Transcript
- Audio description: "Narration describing meaningful visual information not available in audio." — Source: W3C WAI: Audio and video media
- Fallback content: "Content inside audio/video that is rendered only when the element is unsupported." — Source: WHATWG: Embedded content — Fallback content
Mental model: media plus an equivalent purpose
img embeds an image; it does not explain why the image is present. alt supplies a text alternative appropriate to this particular context. Ask: if the image were unavailable, what purpose or information would be missing?
An informative profile photo might use alt="Asha Rao speaking at a web development meetup" if that context matters. If nearby text already identifies Asha and the photo adds only atmosphere, alt="" can be correct. “Image of” is usually redundant because software already identifies an image. Filenames, camera details, and keyword stuffing are not useful alternatives.
Never omit alt as a shortcut for decoration. An empty attribute deliberately tells assistive technology to ignore the image; a missing attribute can produce inconsistent announcements, sometimes including the filename.
Images and stable layout
<img
src="images/profile.webp"
alt="Asha Rao presenting a semantic HTML diagram"
width="800"
height="600">
src identifies the resource. width and height are unitless pixel dimensions describing the source's aspect ratio. Browsers can reserve that shape before download, reducing layout shift. CSS can later make the image responsive while retaining the ratio. Do not lie about the ratio to force visual cropping; use CSS for presentation and provide accurate dimensions.
Choose an appropriate encoded format and dimensions. Photographs often compress well as AVIF or WebP with suitable fallbacks according to project support; logos and diagrams may suit SVG; simple screenshots may suit PNG. Format choice is contextual. Resize and compress rather than sending a 12-megapixel photo for a small profile card.
Below-the-fold images can use loading="lazy", but do not lazily load the likely largest above-the-fold/hero image because that can delay it. Native lazy loading is a hint, not a guarantee.
Figures and captions
Use figure when image and caption form a self-contained unit:
<figure>
<img
src="images/html-plan.webp"
alt="Boxes show header, navigation, main content, and footer in source order"
width="1200"
height="675">
<figcaption>My first plan for the portfolio page structure.</figcaption>
</figure>
Do not duplicate the caption word for word in alt. The caption identifies or contextualizes the figure for everyone; alt replaces visual information needed to understand the image. For a complex chart, a short alt identifies it and the page should provide the full data or explanation nearby.
Audio and video
<audio controls>
<source src="media/introduction.ogg" type="audio/ogg">
<source src="media/introduction.mp3" type="audio/mpeg">
<p><a href="media/introduction.mp3">Download the audio introduction</a>.</p>
</audio>
controls exposes browser playback controls. Multiple source elements allow supported alternatives; order can influence selection. Fallback content is used when the element is unsupported, not as a transcript for modern browsers, so place a transcript link outside the player too.
<video controls width="1280" height="720" poster="images/project-tour-poster.webp">
<source src="media/project-tour.webm" type="video/webm">
<source src="media/project-tour.mp4" type="video/mp4">
<track
kind="captions"
src="media/project-tour.en.vtt"
srclang="en"
label="English"
default>
<p><a href="media/project-tour.mp4">Download the project tour video</a>.</p>
</video>
<p><a href="project-tour-transcript.html">Read the project tour transcript</a>.</p>
Provide accurate captions for prerecorded synchronized media. Captions include meaningful sounds, not only dialogue. A transcript helps many users but does not automatically replace synchronized captions. Meaningful visual information not available in audio needs audio description or another suitable media alternative according to WCAG requirements.
Avoid autoplay, especially with sound. It surprises users, consumes data, can interfere with screen readers, and is often browser-blocked. controls is a boolean attribute; controls="false" still enables it.
Image selection and loading priority
Responsive image syntax answers which image file should be fetched. Loading attributes answer when or how urgently it should be fetched. Keep those decisions separate.
<img
src="bakery-800.jpg"
srcset="bakery-480.jpg 480w, bakery-800.jpg 800w, bakery-1280.jpg 1280w"
sizes="(max-width: 600px) 100vw, 50vw"
width="800"
height="533"
alt="Rina shaping sourdough loaves"
fetchpriority="high">
fetchpriority accepts high, low, or auto. It is a hint to the browser, not an order. Reserve high for genuinely important early resources such as a likely hero/LCP image; marking every image high removes the browser's ability to prioritize effectively.
For images below the initial viewport, loading="lazy" can defer network work until the image is nearer to being needed:
<img src="gallery-12.jpg" alt="Finished croissants on a cooling rack" width="640" height="426" loading="lazy">
Do not lazy-load the primary above-the-fold image merely because the attribute exists. That can delay the largest visible content.
decoding="async" may allow image decoding to happen without blocking other presentation work, but it is also only a hint. Use it when measurement or a platform convention justifies it rather than adding every performance attribute mechanically.
Guided example: improve the About page
Create images/ and put an optimized profile.webp there. Record its actual pixel dimensions. Add:
<main>
<h1>About Asha Rao</h1>
<figure>
<img
src="images/profile.webp"
alt="Asha Rao reviewing a website outline on a whiteboard"
width="800"
height="600">
<figcaption>Planning content before writing markup.</figcaption>
</figure>
<p>I focus on robust, accessible foundations.</p>
<h2 id="skills">Current skills</h2>
<ul>
<li>Semantic document structure</li>
<li>Accessible text and links</li>
</ul>
</main>
Check the context. The alt contributes the whiteboard activity; the caption explains its significance. If the paragraph already said exactly that, shorten one to avoid repetition. Rename the image deliberately, verify case, and test by temporarily changing src: useful alternate text should preserve purpose when the image fails.
In browser network tools, inspect transfer size and resource dimensions. Set network throttling only as a local test. Reload and observe whether reserved dimensions prevent following text from moving.
Intermediate example: project demo media
On projects/weather.html, add a screenshot and narrated demo. A screenshot containing important interface text requires that information in nearby prose, not an enormous alt:
<figure>
<img
src="../images/weather-project.webp"
alt="Weather project showing Chennai at 31 degrees Celsius with cloudy conditions"
width="1440"
height="900"
loading="lazy">
<figcaption>The forecast summary in the first project prototype.</figcaption>
</figure>
<h2>Demo</h2>
<video controls width="1280" height="720" poster="../images/weather-demo-poster.webp">
<source src="../media/weather-demo.webm" type="video/webm">
<track kind="captions" src="../media/weather-demo.en.vtt" srclang="en" label="English" default>
<p><a href="../media/weather-demo.webm">Download the weather demo</a>.</p>
</video>
<p><a href="weather-transcript.html">Read the demo transcript</a>.</p>
The nested page uses ../ for shared folders. Lazy loading is reasonable for a screenshot below introductory text, but evaluate actual placement. Test captions with sound muted. Test the transcript without playing media.
Advanced optional extension: responsive source selection
Without covering full responsive image art direction yet, investigate srcset and sizes:
<img
src="images/profile-800.webp"
srcset="images/profile-400.webp 400w, images/profile-800.webp 800w"
sizes="(max-width: 500px) 400px, 800px"
alt="Asha Rao reviewing a website outline on a whiteboard"
width="800"
height="600">
The browser chooses an appropriate candidate based on viewport, device pixel density, and sizes. This is a performance hint, not a guarantee that a particular file is selected. Incorrect sizes can cause unnecessary downloads. Preserve the same content and aspect ratio across candidates; art direction uses picture and requires more careful alternative-text reasoning.
Use <picture> when the crop or composition must change, not merely because the viewport changed:
<picture>
<source media="(max-width: 40rem)" srcset="images/profile-portrait.webp">
<img src="images/profile-landscape.webp" width="1200" height="675"
alt="Asha Rao reviewing a website outline on a whiteboard">
</picture>
The img remains the fallback and owns the alternative text. The browser evaluates matching sources before downloading an appropriate resource; CSS display: none on an image does not reliably prevent a resource from being discovered, so choose loading behavior in the HTML resource itself. decoding="async" can allow image decoding to avoid delaying other work, but it is a hint. fetchpriority="high" is for a genuinely critical image, not every image near the top of the page.
Common mistakes and debugging
alt="image"or filename: describe purpose in context.- Decorative image with missing
alt: usealt=""deliberately. - Caption duplicated in
alt: divide responsibilities without losing information. - Incorrect relative path or case: resolve from the containing page.
- No dimensions: add the source width and height to reserve aspect ratio.
- Huge source for tiny display: resize, compress, and inspect transfer size.
- Autoplay: remove it unless a rare, user-respecting requirement is proven.
- Transcript inside video fallback only: link it outside for all users.
- Captions that omit sounds: include meaningful non-speech audio.
controls="false": boolean presence means true; omit it only if another accessible controller exists.- Lazy-loading the hero:
loading="lazy"can delay the likely largest visible image; reserve it for content below the initial viewport. - Wrong
sizes: compare the rendered slot with the chosen candidate in Network; a fluid thumbnail can still download a huge source.
Accessibility, security, and performance
Follow the WAI alt decision tree rather than a fixed “describe everything” rule. Functional images name the action or destination; decorative images use empty alt; complex images need equivalent information beyond a short attribute. Media must be keyboard operable, captioned as applicable, and understandable without relying on sound or vision alone.
Media metadata can reveal location, device, or identity; strip unnecessary EXIF data before publishing personal photos. Obtain permission and licenses. Do not embed untrusted third-party media without considering tracking, cookies, and content policy. Optimize dimensions, compression, preload behavior, and formats; measure on slow connections. A poster should be useful and not contain essential text unavailable elsewhere.
Tiered exercises
Level 1: decide alt
Choose alt for a meaningful headshot, a decorative flourish, an icon-only Home link, and a chart. Explain why each differs.
Level 2: integrate
Add one figure and one audio or video item to the portfolio with dimensions, controls, fallback, and appropriate alternatives.
Level 3: audit
Test with images disabled, sound muted, keyboard only, and a slow network. Record one accessibility and one performance improvement.
Level 1: meaningful headshot: concise context-dependent identity/activity; flourish: alt=""; image-only Home link: alt="Home"; chart: short identification in alt plus equivalent data or analysis in nearby HTML.
Level 2: the guided figure plus the video example is complete. Use actual dimensions and existing files, retain controls, provide accurate VTT captions for synchronized speech, and place a transcript link after the player.
Level 3: a sound audit reports whether all purpose remains when images fail, captions convey dialogue and sounds with audio muted, all controls are keyboard reachable, dimensions prevent movement, and transfer sizes match display needs. Example improvement: compress a 4 MB screenshot to a correctly sized 180 KB WebP and add nearby text explaining its displayed results.
Recap and exit questions
Media is not self-explanatory. Give images context-appropriate text alternatives, reserve their aspect ratio, provide captions/transcripts and controls for media, and transfer no more data than the purpose needs.
- When is
alt=""correct? - Why specify both
widthandheight? - Does a transcript always replace captions?
- Why avoid autoplay?
- What is the difference between
altandfigcaption?
Try it with your own example
The fastest way to internalize the alt decision tree is to apply it to a photo where the "right" answer genuinely isn't obvious to you yet — so pick one from your own camera roll right now and work through it honestly.
For Rina's shop, you have been sent three photos: a wide shot of the storefront sign, a close-up of a croissant with visible flaky layers on the product page, and a candid photo of Rina laughing with a regular customer used purely as background texture in the site's footer. Write the alt for each before reading further:
<!-- Storefront: informative — tells visitors what to look for on the street -->
<img src="storefront.webp" alt="Rina's Kitchen storefront with a green awning on Baker Street" width="1200" height="800">
<!-- Croissant: informative in a product context — texture is the point -->
<img src="croissant.webp" alt="A croissant with visibly flaky, golden-brown layers" width="900" height="600">
<!-- Footer candid photo: decorative — the footer text already says everything it needs to -->
<img src="candid.webp" alt="" width="600" height="400">
If your first instinct for the footer photo was to describe it ("Rina laughing with a customer"), you are not wrong to have considered it — that is exactly the judgment call the WAI decision tree exists for. The test is always the same question asked of your image, in your context: does removing this picture remove information, or only atmosphere? Answer that honestly for your own photos and the rest of this lesson becomes muscle memory rather than a rule to memorize.
Further reading: W3C WAI — Alt Decision Tree is the exact flowchart to walk through on your next real image, interactively.
