Skip to content
Document and content / Foundation

Images and Media

Adding images, figures and audio or video with alternatives that everyone can use.

The question How do you add images and media so everyone can use them?

13 min readLesson 04 of 07Read. Try. Understand.

Saved lessons, read marks and notes stay in this browser. Sign in to keep them on all your devices.

On this page

The question

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

Start with the multi-page portfolio from 004. From about.html, trace the relative path to images/profile.webp. Also recall two details that will matter here: an image normally triggers its own HTTP request, and link text should tell the user what the link is for.

The idea

Terminology

Mental model: media plus an equivalent purpose

An img embeds an image, but the element itself does not tell us why the image is on the page. The alt value supplies a text alternative suited to this particular context. A useful test is: if the image disappeared, what information or purpose would the reader lose?

For example, an informative profile photo might use alt="Asha Rao speaking at a web development meetup" when that activity matters. If the surrounding text already identifies Asha and the photo contributes only atmosphere, alt="" may be the right choice. Software already announces that something is an image, so “Image of” is usually noise. Filenames, camera metadata, and keyword stuffing are not useful alternatives.

Do not leave out alt as a way of making an image decorative. An empty attribute is an intentional instruction to assistive technology to ignore the image. A missing attribute can lead to inconsistent announcements, including announcements based on the filename.

Images and stable layout

Change the code, then look at the preview. The preview runs in a sandbox.

Run the code to see the preview.

The preview appears here.

src identifies the resource. The unitless width and height values describe the source dimensions and therefore its aspect ratio in pixels. With them, the browser can reserve the correct shape before the download completes, which reduces layout shift. CSS can still make the image responsive later while preserving that ratio. Do not provide false dimensions to force a crop; use CSS for presentation and keep the HTML dimensions accurate.

The file format and dimensions should match the job. Photographs often compress well as AVIF or WebP, with suitable fallbacks for the browsers the project supports. Logos and diagrams may be good SVG candidates, while simple screenshots may suit PNG. There is no universal winner. Resize and compress the asset instead of sending a 12-megapixel photograph to fill a small profile card.

For images below the fold, loading="lazy" can be useful. Avoid applying it to the likely largest above-the-fold or hero image, because delaying that request can delay the visible content. Native lazy loading is a browser hint, not a guarantee.

Figures and captions

Use figure when the image and its caption make a self-contained unit:

Change the code, then look at the preview. The preview runs in a sandbox.

Run the code to see the preview.

The preview appears here.

The caption and alternative text have different jobs, so do not copy the caption word for word into alt. The caption identifies or contextualizes the figure for everyone; alt supplies visual information needed to understand it when the image cannot be perceived. For a complex chart, keep alt short enough to identify the chart and provide its complete data or explanation elsewhere on the page.

Audio and video

Change the code, then look at the preview. The preview runs in a sandbox.

Run the code to see the preview.

The preview appears here.

controls exposes the browser’s native playback controls. Multiple source elements offer alternatives that the browser can support; their order can affect which one is selected. The content inside the element is fallback content for an unsupported element, not a transcript that modern browsers will display alongside the player. Put a transcript link outside the player as well.

Change the code, then look at the preview. The preview runs in a sandbox.

Run the code to see the preview.

The preview appears here.

Prerecorded synchronized media needs accurate captions. Captions include meaningful sounds, not just spoken words. A transcript is useful to many people, but it does not automatically provide synchronized captions for a video. If important visual information is absent from the audio, provide audio description or another suitable media alternative in line with WCAG requirements.

Autoplay, particularly autoplay with sound, is usually a poor default. It can surprise users, consume data, interfere with screen readers, and be blocked by the browser. Also remember that controls is boolean: controls="false" still enables the controls because the attribute is present.

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. Treat those as separate decisions.

Change the code, then look at the preview. The preview runs in a sandbox.

Run the code to see the preview.

The preview appears here.

fetchpriority accepts high, low, or auto. It is a hint, not an order. Reserve high for a genuinely important early resource, such as a likely hero image, often the Largest Contentful Paint (LCP) element of the page. If every image is marked high, the browser loses useful information about which work deserves priority.

For content below the initial viewport, loading="lazy" can defer network work until the image is closer to being needed:

Change the code, then look at the preview. The preview runs in a sandbox.

Run the code to see the preview.

The preview appears here.

Do not lazy-load the primary above-the-fold image simply because the attribute is available. That can postpone the largest visible content.

decoding="async" may let image decoding proceed without blocking other presentation work, but it remains a hint. Add it when measurement or a platform convention supports it, not as a reflexive performance checklist item.

Common mistakes and debugging

  • alt="image" or filename: describe purpose in context.

  • Decorative image with missing alt: use alt="" 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

Use the WAI alt decision tree instead of applying a blanket “describe everything” rule. A functional image names its action or destination, a decorative image gets empty alt, and a complex image needs its equivalent information somewhere beyond a short attribute. Media should be keyboard operable, captioned where applicable, and understandable without depending on sound or vision alone.

Media metadata may expose location, device, or identity, so strip unnecessary EXIF data before publishing personal photos. Confirm permissions and licenses. Before embedding third-party media, consider tracking, cookies, and content policy. Optimize dimensions, compression, preload behavior, and formats, then measure on slow connections. A poster should be useful without putting essential text only in the poster image.

Image maps

When an image has clickable regions

An image map places clickable areas on one image. img with usemap points to a map element by name, and each area gives a shape, coordinates, a destination, and alt text.

Use an image map only when the regions are spatial, such as a floor plan or a map. For a list of destinations, a normal list of links is clearer and easier to use from the keyboard. Every area needs alt text, because a screen reader announces only that text.

The example below uses a placeholder image path. Replace it with a real image before relying on the coordinates.

Change the code, then look at the preview. The preview runs in a sandbox.

Run the code to see the preview.

The preview appears here.

Worked example

Guided example: improve the About page

Create images/ and place an optimized profile.webp inside it. Record the file’s actual pixel dimensions, then add:

Change the code, then look at the preview. The preview runs in a sandbox.

Run the code to see the preview.

The preview appears here.

Now judge the image in context. The alt supplies the whiteboard activity, while the caption explains why that activity matters. If the paragraph already states exactly the same thing, shorten one of them rather than making a screen-reader user hear the information twice. Give the file a deliberate name, verify its case, and test failure by temporarily changing src. A useful alternative should preserve the image’s purpose when the resource cannot load.

Open the browser’s network tools and inspect both transfer size and resource dimensions. Use throttling only as a local test. Reload and watch whether the reserved dimensions keep the text below the figure from moving as the image arrives.

Intermediate example: project demo media

On projects/weather.html, add a screenshot and a narrated demo. If the screenshot contains important interface text, put that information in nearby prose instead of writing an enormous alt value:

Change the code, then look at the preview. The preview runs in a sandbox.

Run the code to see the preview.

The preview appears here.

Because this page is nested, shared folders are reached with ../. Lazy loading is sensible for a screenshot below the introductory content, but its actual position still matters. Test the captions with sound muted, and test the transcript independently rather than assuming that the video must play.

Advanced optional extension: responsive source selection

Without covering full responsive-image art direction yet, investigate srcset and sizes:

Change the code, then look at the preview. The preview runs in a sandbox.

Run the code to see the preview.

The preview appears here.

The browser selects a candidate using the viewport, device pixel density, and the sizes estimate. This is a performance hint, not a promise that one particular file will always be chosen. A wrong sizes value can cause an unnecessarily large download. Keep the subject and aspect ratio consistent across candidates; changing the crop or composition is art direction, which uses picture and requires more careful alternative-text decisions.

Use <picture> when the crop or composition needs to change, not merely because the viewport changed:

Change the code, then look at the preview. The preview runs in a sandbox.

Run the code to see the preview.

The preview appears here.

The img is the fallback and owns the alternative text. The browser checks matching sources before downloading an appropriate resource. Setting display: none in CSS does not reliably stop an image resource from being discovered, so make loading choices in the HTML resource itself. decoding="async" can let decoding avoid delaying other work, but it is still a hint. fetchpriority="high" belongs on a genuinely critical image, not on every image near the top of the page.

Try it

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 case is different.

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 improvement and one performance improvement.

Complete solutions

    Try it with your own example

    The quickest way to internalize the alt decision tree is to use it on a photo whose answer is not immediately obvious. Pick one from your own camera roll and work through the context rather than guessing from the subject alone.

    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:

    Change the code, then look at the preview. The preview runs in a sandbox.

    Run the code to see the preview.

    The preview appears here.

    If you initially described the footer photo (“Rina laughing with a customer”), that is a reasonable question to consider. It is also the judgment call the WAI decision tree is designed to help with. Ask the same question of the image in its actual context: does removing the picture remove information, or only atmosphere? Applying that honestly to your own photos turns the decision into a usable habit 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.

    Check yourself

    Recap and exit questions

    Media does not explain itself. Give images context-appropriate text alternatives, reserve their aspect ratio, provide captions/transcripts and controls for media, and avoid transferring more data than the purpose requires.

    1. When is alt="" correct?

    2. Why specify both width and height?

    3. Does a transcript always replace captions?

    4. Why avoid autoplay?

    5. What is the difference between alt and figcaption?

    An image is purely decorative, and the surrounding text already says everything it conveys. Which alt value is correct?

    Choose an answer, then check it.

    Why set width and height on an img?

    Choose an answer, then check it.

    What’s next

    The idea to take with you

    Media does not explain itself. Give images context-appropriate text alternatives, reserve their aspect ratio, provide captions/transcripts and controls for media, and avoid transferring more data than the purpose requires.

    A small marker for this page. Sign in to save your progress.

    Your own words, in the margin.

    — / 250

    Loading your note…