For years, putting a video on a website meant installing external plug-ins such as Flash. HTML5 changed that with the video element, which plays video natively, with the browser's own controls and without relying on third parties. In this lesson you will learn how to insert a video with controls, how to configure its playback (automatic, looped, muted), how to show a poster image, how to decide how much should be preloaded, how to offer several formats so that it works in any browser and, most importantly, how to add subtitles in the WebVTT format. By the end, The Blue Cup's gallery will have an introductory video with a poster image and English subtitles.
Contents
- The
videoelement - Playback attributes:
controls,autoplay,muted,loopandplaysinline - The poster image:
poster - How much to download in advance:
preload - Several formats with
sourceandtype - Fallback content
- Subtitles with
trackand WebVTT - Video formats for the web
- YouTube or Vimeo videos
- Project: the introductory video in the gallery
The video element
The simplest way to embed a video is this:
src: path of the video file, with the same rules as inimgora. The project's media resources go in themedia/folder.controls: a Boolean attribute that shows the browser's controls (play, pause, volume, progress bar, full screen). Without it, the video appears with no buttons at all and the user can't start it.widthandheight: dimensions in pixels, without units. As with images, they let the browser reserve the space before the video loads and avoid layout shifts.
Unlike img, video isn't an empty element: it has a closing tag and can contain other elements (sources, subtitles and fallback content), as you will see shortly.
Each browser draws its own controls, so their appearance varies between Chrome, Firefox and Safari. That's normal and nothing to worry about: native controls are accessible with the keyboard and with screen readers, which is hard to achieve with home-made controls.
Playback attributes: controls, autoplay, muted, loop and playsinline
| Attribute | Type | Effect |
|---|---|---|
controls |
Boolean | Shows the playback controls |
autoplay |
Boolean | Tries to start playing as soon as it can |
muted |
Boolean | Starts with no sound |
loop |
Boolean | Starts again when it finishes |
playsinline |
Boolean | On mobiles (especially iPhones), plays within the page instead of switching to full screen |
Remember that Boolean attributes work simply by being present, as you learnt in Tags, Elements and Attributes: autoplay="false" still turns on autoplay. To turn it off, remove it.
autoplay and browser policies
Browsers block autoplay with sound: nobody wants to open a page and have something start playing without asking for it. So, in practice, autoplay only works reliably when it's accompanied by muted:
<!-- Ambience video: short, silent, looped -->
<video src="media/steaming-cup.mp4" autoplay muted loop playsinline width="640" height="360"></video>This pattern is the typical one for a decorative background video: a steaming cup, the steam from the coffee machine… A few precautions:
- Keep it short and lightweight: it will always be downloaded, even if the visitor doesn't watch it.
- If the video lasts more than five seconds, the user must be able to pause it (this is an accessibility requirement: continuous movement is distracting and bothers some people). The simplest solution is to add
controls. - Never use
autoplayfor a video with important information or speech: let users decide when to watch it.
The poster image: poster
Until the video plays, the browser shows its first frame, which is often black or unrepresentative. The poster attribute sets a poster image:
<video src="media/intro.mp4" controls width="640" height="360" poster="img/intro-poster.jpg"></video>- The image must have the same aspect ratio as the video (16:9 here) so that no bars appear.
- It's an ordinary image, so follow the format and file size advice in Adding Images.
- It doesn't take an
alt: the video is described by the text around it (a heading or a paragraph saying what it contains).
How much to download in advance: preload
The preload attribute suggests to the browser how much of the video it should download before the user presses "play":
| Value | What it downloads | When to use it |
|---|---|---|
none |
Nothing | Videos that probably won't be watched, pages with lots of videos, saving data |
metadata |
Only the basic data: duration, dimensions, first frame | A balanced option for most cases |
auto |
It may download the whole video | When it's almost certain the user will watch it (the video is the page's main content) |
It's only a suggestion: the browser may ignore it (for example, in data saver mode). And if the video has autoplay, it will be downloaded anyway. You will come back to resource loading in Performance and Resource Loading.
Several formats with source and type
Not all browsers have always supported the same video formats. To make sure the video plays in all of them, you can offer several versions with source elements inside video, instead of the src attribute:
<video controls width="640" height="360" poster="img/intro-poster.jpg">
<source src="media/intro.webm" type="video/webm">
<source src="media/intro.mp4" type="video/mp4">
</video>How it works:
- The browser reads the
sourceelements in order. - Thanks to
type, it knows the format without downloading the file. If it doesn't support it, it moves on to the next one. - It uses the first one it can play and ignores the rest.
That's why:
- Put the most efficient format first (WebM, lighter) and the most compatible one afterwards (MP4).
- Always write
type: without it, the browser would have to start downloading each file to find out whether it can use it. sourceis an empty element, with no closing tag.- If you use
source, don't putsrconvideo: it would take priority over thesourceelements.
Fallback content
Anything you write inside video that isn't a source or a track is fallback content: it's only shown in browsers that don't understand the video element. These are very rare today, but it's good practice to offer a link to the file:
<video controls width="640" height="360">
<source src="media/intro.webm" type="video/webm">
<source src="media/intro.mp4" type="video/mp4">
<p>Your browser can't play this video. <a href="media/intro.mp4">Download the introductory video (MP4, 8 MB)</a>.</p>
</video>Careful: the fallback content doesn't appear if the browser understands video but can't find any compatible format, or the file doesn't exist. In that case you will see an empty player or one showing an error message. Nor is it an accessible substitute for the video: that's what subtitles and transcripts are for.
Subtitles with track and WebVTT
Subtitles are essential for deaf and hard-of-hearing people, but also for anyone watching the video on public transport without headphones or who doesn't speak the language well. They are added with the (empty) track element, inside video:
| Attribute | Meaning |
|---|---|
kind |
Type of track: subtitles (translation or transcription of the dialogue), captions (dialogue plus relevant sounds, for deaf people), descriptions (description of what can be seen), chapters (chapters) |
src |
Path to the subtitle file in .vtt format |
srclang |
Language of the track (required if kind="subtitles") |
label |
Name that appears in the player's subtitles menu |
default |
Boolean: turns this track on by default |
You can add several tracks, one per language; the user will choose from the player's menu:
<track kind="subtitles" src="media/intro.en.vtt" srclang="en" label="English" default>
<track kind="subtitles" src="media/intro.es.vtt" srclang="es" label="Español">The WebVTT format
A WebVTT (.vtt) file is a text file that you can create with VS Code. This is media/intro.en.vtt:
WEBVTT
00:00:00.000 --> 00:00:04.000
Welcome to The Blue Cup,
your neighbourhood café and bakery.
00:00:04.500 --> 00:00:09.000
Every morning, before we open,
we bake the bread and the croissants.
00:00:09.500 --> 00:00:14.000
[Sound of the coffee machine]
And we roast our own coffee.
00:00:14.500 --> 00:00:18.000
We look forward to seeing you from 8:00 to 20:00.Line by line:
WEBVTT: a mandatory first line that identifies the format. Without it, the file doesn't work.- A blank line separates each block, called a cue.
00:00:00.000 --> 00:00:04.000: when the text appears and when it disappears, inhours:minutes:seconds.milliseconds. The-->arrow has a space on each side.- The following lines are the text shown (one or two short lines, so that there is time to read them).
[Sound of the coffee machine]: indicating relevant sounds in square brackets is common in subtitles for deaf people.
Save the file in UTF-8 (VS Code does this by default) so that characters such as the "é" in "café" display correctly.
Important: for security reasons, browsers don't load
trackfiles when you open the page withfile:///. Test subtitles with Live Server. And if the track is on another domain, additional server configuration is needed; the simplest solution is to host it alongside your page.
Video formats for the web
A video file is a container (.mp4, .webm) that holds images and sound compressed with particular codecs. For the web, two containers cover every need:
| Format | MIME type (type) |
Common codecs | Compatibility | Notes |
|---|---|---|---|---|
| MP4 | video/mp4 |
H.264 + AAC | Universal | The safe option; if you only offer one format, make it this one |
| WebM | video/webm |
VP9 or AV1 + Opus | All modern browsers | Lighter files at the same quality |
| Ogg (Theora) | video/ogg |
Theora + Vorbis | Limited | Historical; no longer recommended |
Tips:
- Compress videos for the web. A one-minute introductory video shouldn't be more than a few MB. Free tools such as HandBrake let you export to MP4 (H.264) for the web.
- Adjust the resolution to how it will be viewed: a video displayed 640 pixels wide doesn't need to be in 4K.
- Remember that video uses up your visitors' data and your server's bandwidth.
YouTube or Vimeo videos
If the video is published on a platform such as YouTube or Vimeo, you don't use the video element: the platform doesn't give you the file but an embed code ("Share" button → "Embed") based on the iframe element, which displays a page from the platform inside yours. Advantages: they host the video, adapt it to each user's connection and it doesn't use your bandwidth. Disadvantages: you depend on a third party, it loads their scripts and it may track your visitors. You will learn how to use iframe properly in Using iframes (Module 7).
video with your own file |
iframe from a platform |
|
|---|---|---|
| Where the file is | On your server | On the platform |
| Control over the player | Complete | Whatever the platform allows |
| Bandwidth | Yours | The platform's |
| Privacy | No third parties | The platform may track visitors |
Project: the introductory video in the gallery
You are going to add The Blue Cup's introductory video to gallery.html. Prepare these files (it can be a short video recorded on your mobile, or any 16:9 test video):
| File | Content |
|---|---|
media/intro.mp4 |
Introductory video (640 × 360, MP4 H.264) |
media/intro.webm |
The same video in WebM (optional) |
media/intro.en.vtt |
English subtitles (the WebVTT file from this lesson) |
img/intro-poster.jpg |
Poster image, 640 × 360 |
In gallery.html, after the products section, add:
<h2>Get to know The Blue Cup on video</h2>
<p>A minute in our bakery: this is how we make the bread, the croissants and the coffee every morning.</p>
<video controls preload="metadata" width="640" height="360" poster="img/intro-poster.jpg">
<source src="media/intro.webm" type="video/webm">
<source src="media/intro.mp4" type="video/mp4">
<track kind="subtitles" src="media/intro.en.vtt" srclang="en" label="English" default>
<p>Your browser can't play this video. <a href="media/intro.mp4">Download the introductory video (MP4, 8 MB)</a>.</p>
</video>Review each decision:
- A heading and a paragraph before the video: they explain what it contains, since the video has no
alt. controls: the user decides when to watch it; noautoplay, because it has sound and speech.preload="metadata": the gallery has lots of images; there's no point in downloading the whole video if perhaps nobody watches it.poster: an attractive poster image instead of a black frame.- Two
sourceelements: WebM first (lighter) and MP4 as the universal option. If you haven't created the WebM version, delete that line; the MP4 is enough. trackwithdefault: subtitles turned on from the start, because many people watch videos without sound.- Fallback content with a descriptive link that states the format and size, as you learnt in Special Links.
Open it with Live Server (remember: with file:/// the subtitles don't load), play it and check in the player's menu that the "English" track appears. In the Network panel of DevTools, notice that before you press play only a small part of the video is downloaded, thanks to preload="metadata".
Common Mistakes and Tips
- Forgetting
controls: the video appears with no buttons and there's no way to play it. - Using
autoplaywithoutmuted: the browser will block autoplay. - Writing
autoplay="false"to turn it off: since it's Boolean, it turns it on. Remove the attribute. - Leaving out
typeon thesourceelements: the browser has to download files to find out whether it can use them. - Putting
srconvideoas well assourceelements: thesourceelements are ignored. - Forgetting the
WEBVTTline at the start of the subtitle file, or using commas instead of full stops in the times (00:00:04,000is SRT format, not WebVTT). - Testing subtitles with
file:///: they don't load; use Live Server. - Uploading uncompressed videos of hundreds of MB: the page will be slow to load and will use up your visitors' data.
- Tip: always think about people who can't hear the video (subtitles) and people who can't see it (describe its content in the text or in a transcript).
Exercises
Exercise 1. Write the code for a decorative background video media/steam.mp4 of 640 × 360 that starts by itself, repeats indefinitely, has no sound and plays within the page on iPhones. Since it lasts 12 seconds, which attribute should you add to meet accessibility requirements?
Exercise 2. Create the file media/intro.es.vtt with the first two blocks of subtitles translated into Spanish, and write the track line that adds it to the gallery video without it being turned on by default.
Exercise 3. Find and correct the errors:
<video src="media/workshop.mp4" autoplay="false" width="640px">
<source src="media/workshop.webm">
<track src="media/workshop.vtt" kind="subtitles">
</video>Solutions
Solution 1.
<video src="media/steam.mp4" autoplay muted loop playsinline controls width="640" height="360"></video>autoplay + muted allow autoplay; loop repeats it; playsinline prevents full screen on iPhones. Since it lasts more than five seconds and repeats endlessly, users must be given a way to pause it: controls.
Solution 2.
WEBVTT
00:00:00.000 --> 00:00:04.000
Bienvenidos a The Blue Cup,
la cafetería-obrador de tu barrio.
00:00:04.500 --> 00:00:09.000
Cada mañana, antes de abrir,
horneamos el pan y los cruasanes.Without default, the track appears in the player's menu, but the user has to turn it on. Only one track of each kind should have default.
Solution 3.
<video controls width="640" height="360" preload="metadata">
<source src="media/workshop.webm" type="video/webm">
<source src="media/workshop.mp4" type="video/mp4">
<track kind="subtitles" src="media/workshop.en.vtt" srclang="en" label="English">
<p><a href="media/workshop.mp4">Download the workshop video (MP4)</a>.</p>
</video>autoplay="false"turned autoplay on (and with sound, which the browser would block): it's removed andcontrolsis added.widthdoesn't takepx, andheightwas missing.- The
srconvideooverrode thesourceelements: the MP4 becomes anothersource, and each one has itstype. - The subtitle track needs
srclang(required withsubtitles) and should be given alabel. The file name now indicates the language, as in the project. - Fallback content is added.
Conclusion
You now know how to embed video natively with the video element: showing the controls, combining autoplay with muted (and respecting browser policies), repeating with loop, adding a poster image with poster, managing downloads with preload, offering several formats with source and type (WebM and MP4), providing fallback content and adding subtitles with track and WebVTT files. You also know that YouTube or Vimeo videos are embedded with iframe, which you will see in Module 7. The Blue Cup's gallery now includes an introductory video with a poster image, moderate preloading and English subtitles. In the next lesson, Using the Audio Element, you will complete the media section with sound: the atmosphere of the café and an interview with the head baker, accompanied by its transcript.
HTML Course
Module 1: Introduction to HTML
- What Is HTML?
- Setting Up Your Work Environment
- Basic Structure of an HTML Document
- Tags, Elements and Attributes
- Creating Your First HTML Page
- File Organisation and Paths
Module 2: Text Formatting in HTML
- Headings and Paragraphs
- Text Formatting Tags
- Lists: Ordered, Unordered and Description Lists
- Block Quotes and Preformatted Text
- Block and Inline Elements: div and span
Module 3: Links and Media in HTML
- Creating Hyperlinks
- Special Links: Anchors, Email, Phone and Downloads
- Adding Images
- Embedding Videos
- Using the Audio Element
Module 4: Tables in HTML
- Basic Table Structure
- Table Head, Body and Foot
- Merging Cells: colspan and rowspan
- Accessible Tables: caption, scope and headers
- Styling Tables
Module 5: Forms in HTML
- Creating a Basic Form
- Form Elements: input, textarea and select
- HTML5 Input Types
- Labels and Grouping: label, fieldset, legend and datalist
- Form Attributes and Validation
- Submitting Forms
Module 6: HTML5 Semantic Elements
- Introduction to Semantic HTML
- header, nav and footer
- article, section and aside
- main and figure
- Other Semantic Elements: time, address, details and dialog
Module 7: Advanced HTML Techniques
- HTML Entities
- Using iframes
- Data Attributes
- Metadata: meta, SEO and Open Graph
- Microdata and Structured Data
- Graphics in HTML: SVG and canvas
Module 8: Integrating HTML and CSS
- Linking CSS to HTML
- Inline, Internal and External CSS
- Basic CSS Selectors
- The Box Model
- Styling HTML Elements
- Introduction to Layout with Flexbox and Grid
Module 9: Responsive Web Design
Module 10: Best Practices and Accessibility
- HTML Best Practices
- Validating HTML Code
- Web Accessibility Basics
- Using ARIA Roles and Attributes
- Accessibility Testing
- Performance and Resource Loading
