AI Workshop: learn to build apps with AI →
HTML Media: How to Embed Video in HTML

Join the AI Workshop and learn to build real-world apps with AI. A hands-on, practical program to level up your skills.


The video tag allows you to embed video content in your HTML pages.

Basic Usage

Reference a video file with the src attribute:

<video src="file.mp4"></video>

To display the built-in controls, add the controls attribute:

<video src="file.mp4" controls></video>

Common Attributes

poster

Display a custom thumbnail image before the video plays:

<video src="video.mp4" poster="thumbnail.png" controls></video>

Without a poster, the browser displays the first frame of the video.

autoplay

Play the video automatically. Many browsers require muted to be set for autoplay to work:

<video src="file.mp4" controls autoplay muted></video>

loop

Restart the video when it reaches the end:

<video src="file.mp4" controls loop></video>

width and height

Set the dimensions of the video player:

<video src="video.mp4" controls width="800" height="450"></video>

preload

Control how the browser preloads the video:

<video src="video.mp4" preload="auto"></video>

Values: none, metadata (default), or auto.

Multiple Sources

To support different video formats, use the source element:

<video controls>
  <source src="video.webm" type="video/webm">
  <source src="video.mp4" type="video/mp4">
</video>

The browser will use the first format it supports.

Fallback Content

Add text for browsers that don’t support the video element:

<video src="video.mp4" controls>
  Your browser does not support the video element.
</video>

JavaScript Events

You can listen for various events on video elements:

const video = document.querySelector('video')

video.addEventListener('play', () => {
  console.log('Video started playing')
})

video.addEventListener('pause', () => {
  console.log('Video paused')
})

video.addEventListener('ended', () => {
  console.log('Video finished')
})

Common events include: play, pause, ended, timeupdate, and volumechange.

CORS

Videos from other origins (domains) are subject to CORS restrictions. The server hosting the video must include appropriate CORS headers to allow cross-origin playback.

Lessons in this unit:

0: Introduction
1: How to Add Images in HTML
2: How to Create Responsive Images with srcset and picture
3: How to Embed Audio in HTML
4: ▶︎ How to Embed Video in HTML
5: How to Embed External Content with iframe
6: An in-depth SVG tutorial
7: The WebP Image Format