HTML5 introduces the <video>
element, which allows you to embed videos directly into your web pages without the need for third-party plugins like Flash. Below is a beginner’s guide to using HTML video.
Basic HTML Video Structure:
Here’s a basic structure for embedding a video in HTML:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>HTML Video Example</title> </head> <body> <video width="640" height="360" controls> <source src="example.mp4" type="video/mp4"> Your browser does not support the video tag. </video> </body> </html>
- The
<video>
element is used to embed a video. - The
width
andheight
attributes set the dimensions of the video player. - The
controls
attribute adds playback controls (play, pause, volume, etc.). - The
<source>
element is used to specify the video file and its type.
Video File Formats:
Different browsers support different video formats. To ensure compatibility across browsers, provide multiple sources in different formats. The <source>
element within the <video>
tag helps with this:
<video width="640" height="360" controls> <source src="example.mp4" type="video/mp4"> <source src="example.webm" type="video/webm"> Your browser does not support the video tag. </video>
- In this example, the browser will try to play the MP4 file first and, if not supported, fall back to the WebM file.
Adding Poster (Preview Image):
You can add a poster attribute to display an image before the video starts:
<video width="640" height="360" controls poster="preview.jpg"> <source src="example.mp4" type="video/mp4"> <source src="example.webm" type="video/webm"> Your browser does not support the video tag. </video>
Autoplay and Loop:
You can use the autoplay
and loop
attributes to make the video play automatically and loop:
<video width="640" height="360" controls autoplay loop> <source src="example.mp4" type="video/mp4"> <source src="example.webm" type="video/webm"> Your browser does not support the video tag. </video>
Responsive Video:
To make the video player responsive, you can use CSS or the width
attribute set to a percentage:
<video width="100%" height="auto" controls> <source src="example.mp4" type="video/mp4"> <source src="example.webm" type="video/webm"> Your browser does not support the video tag. </video>
Accessibility:
Provide a text message inside the <video>
element that will be displayed if the browser does not support video:
<video width="640" height="360" controls> <source src="example.mp4" type="video/mp4"> <source src="example.webm" type="video/webm"> Your browser does not support the video tag. </video>
This message will be shown if the browser doesn’t support the video element.
Remember to provide alternative content for users who cannot view or interact with the video, ensuring your website remains accessible to everyone.