FullStack Course LogoFullStack Course
Module: HTML
HTML·005·11 MIN READ

005: Images and Media

TOPICS COVERED: 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

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.

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

html
<img
  src="images/profile.webp"
  alt="Asha Rao presenting a semantic HTML diagram"
  width="800"
  height="600">

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:

html
<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>

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

html
<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 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.

html
<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>

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.

html
<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, not an order. Reserve high for a genuinely important early resource, such as a likely hero or LCP image. 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:

html
<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 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.

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:

html
<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>

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:

html
<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>

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:

html
<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 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:

html
<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 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.

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.

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.

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 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?

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:

html
<!-- 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 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.

Official references

Reader page: /html/lesson/005/images-and-media