Video, audio and embeds

HTML · Practical · 10 min

Native media elements replace plugins and work everywhere, but captions and iframe sandboxing are easy to forget.

<video> and <audio> play media natively.

  • controls shows the browser's player UI. Without it, the user can't play or pause unless you build controls.
  • Offer several encodings with <source src type> children; the browser plays the first it supports. MP4 (H.264) plays everywhere; WebM or AV1 are smaller.
  • poster sets a preview image; preload="none" or "metadata" saves bandwidth.
  • Browsers block autoplay with sound. autoplay only works reliably with muted, and playsinline keeps iOS from going full-screen.

Captions come from a <track kind="captions" src="en.vtt" srclang="en" label="English"> pointing at a WebVTT file. They're essential for deaf users and for anyone watching without sound.

An <iframe> embeds another page, like a map, a video player or a payment widget. It's a whole browsing context, so treat it with care:

  • Give it a title describing its content, for screen readers.
  • loading="lazy" defers off-screen embeds, which are often heavy.
  • sandbox restricts the embedded page; add back only what it needs, e.g. sandbox="allow-scripts allow-same-origin".
  • allow grants features such as fullscreen or autoplay.

Sites can refuse to be framed with the X-Frame-Options or CSP frame-ancestors headers, which is why some URLs show an error inside an iframe.

Example

<video controls width="640" height="360" poster="intro-poster.jpg" preload="metadata">
  <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" default>
  Your browser can't play this video. <a href="intro.mp4">Download it</a>.
</video>

<!-- Background loop: must be muted to autoplay -->
<video autoplay muted loop playsinline src="bg-loop.mp4"></video>

<audio controls src="episode-12.mp3"></audio>

<iframe src="https://www.openstreetmap.org/export/embed.html?bbox=44.4,40.1,44.6,40.2"
        title="Map of our office in Yerevan" width="600" height="400"
        loading="lazy"></iframe>

Remember

  • Add controls, multiple sources and a poster to video
  • Autoplay only works muted
  • Captions via track and WebVTT
  • Give iframes a title, lazy-load them, and sandbox untrusted ones

Watch out for

  • Expecting autoplay with sound to work; browsers block it until the user interacts.

Check yourself

  1. A hero video with autoplay doesn't start in Chrome. What's the likely fix?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/video

Builds on

Unlocks

Nothing builds on this yet.