To add a video in HTML, you use the <video>
element along with the <source>
element to specify the video file and its format. Here's how:
-
Use the
<video>
tag: This is the container for your video. You'll need to set attributes likewidth
,height
, andcontrols
. -
Use the
<source>
tag(s): Inside the<video>
tag, use one or more<source>
tags to specify different video formats. This allows the browser to choose the format it supports. -
Include fallback text: Between the opening and closing
</video>
tags, include text that will be displayed if the browser doesn't support the<video>
tag.
Here's a basic example:
<video width="320" height="240" controls>
<source src="movie.mp4" type="video/mp4">
<source src="movie.ogg" type="video/ogg">
Your browser does not support the video tag.
</video>
Explanation:
width
andheight
: These attributes specify the dimensions of the video player.controls
: This attribute adds video controls like play, pause, volume, and fullscreen. If you omit this, the user won't be able to control the video.<source src="movie.mp4" type="video/mp4">
: This specifies the video file (movie.mp4
) and its MIME type (video/mp4
). It's good practice to provide multiple<source>
tags with different formats (like MP4, WebM, and Ogg) to ensure compatibility across different browsers. MP4 is generally the most widely supported format.Your browser does not support the video tag.
: This text will only be displayed if the user's browser doesn't support the HTML5<video>
tag. It's a fallback mechanism.
Common Video Formats and MIME Types:
Format | MIME Type | Browser Support |
---|---|---|
MP4 | video/mp4 |
Widely supported (Chrome, Edge, Firefox, Safari, etc.) |
WebM | video/webm |
Good support (Chrome, Firefox, Edge, Opera) |
Ogg | video/ogg |
Decent support (Firefox, Chrome, Opera, older browsers) |
Additional Attributes:
You can add other attributes to the <video>
tag to customize the video player:
autoplay
: Starts playing the video automatically when the page loads. Use with caution, as it can be annoying to users.loop
: Repeats the video when it reaches the end.muted
: Mutes the video's audio by default.poster
: Specifies an image to display while the video is downloading or until the user hits the play button. Example:<video poster="poster.jpg" ...>
Example with autoplay
, loop
, and muted
:
<video width="320" height="240" controls autoplay loop muted poster="poster.jpg">
<source src="movie.mp4" type="video/mp4">
<source src="movie.ogg" type="video/ogg">
Your browser does not support the video tag.
</video>
In summary, the <video>
tag with the <source>
tag(s) is how you embed a video into an HTML page, allowing for compatibility across various browsers and offering control over the video's presentation and playback.