HTML provides the <video>
element for embedding and playing video content on a web page. Here’s how to use the <video>
element in HTML:
- Basic
<video>
Element:
To embed a video on a web page, use the<video>
element and specify the video source using thesrc
attribute. Example:
<video src="video.mp4" controls></video>
The src
attribute specifies the URL or file path of the video file. The controls
attribute adds playback controls (play, pause, volume, etc.) to the video player.
- Multiple Video Sources:
To ensure compatibility across different browsers and devices, you can provide multiple video sources using the<source>
element within the<video>
element. The browser will automatically select the appropriate source based on compatibility. Example:
<video controls>
<source src="video.mp4" type="video/mp4">
<source src="video.webm" type="video/webm">
<source src="video.ogg" type="video/ogg">
</video>
In this example, three video sources (MP4, WebM, and Ogg) are provided, each with its corresponding MIME type.
- Video Attributes:
The<video>
element supports various attributes to control video playback and appearance. Some commonly used attributes include:
controls
: Adds playback controls to the video player.autoplay
: Specifies that the video should start playing automatically.loop
: Specifies that the video should loop and repeat playback.muted
: Specifies that the video should start playing with muted audio.poster
: Specifies an image to be displayed as a poster before the video starts playing.width
andheight
: Specifies the dimensions of the video player.
Example:
<video src="video.mp4" width="640" height="360" controls autoplay loop muted poster="poster.jpg"></video>
- Captions and Subtitles:
You can add captions or subtitles to your video using the<track>
element within the<video>
element. Example:
<video controls>
<source src="video.mp4" type="video/mp4">
<track src="captions.vtt" kind="captions" srclang="en" label="English">
</video>
In this example, a WebVTT (Web Video Text Tracks) file is used for captions, specifying the source, kind, language, and label of the captions.
The <video>
element provides additional functionality and events that can be accessed and controlled through JavaScript. It allows you to create interactive video experiences by handling events like play, pause, seek, and more.
Remember to consider different video formats and provide fallback options for unsupported browsers or devices to ensure a smooth video playback experience.