Categories
HTML Web development

How to embed the YouTube video in HTML?

How to embed the YouTube video in HTML?

One of the easiest ways to play videos in HTML is to use YouTube.

Converting videos to formats acceptable in HTML (Mp4, WebM, Ogg) can be difficult and time-consuming. The easier way to let the video play on your website is using YouTube.

Use an <iframe> element to embed the video on the website:

<!DOCTYPE html>
<html>
<body>

<iframe src="https://www.youtube.com/embed/o5daeOwl-4Q">
</iframe>

</body>
</html>

Output:

Each YouTube video has a unique Id (like o5daeOwl-4Q). To check which Id has your chosen video open to video in YouTube and press on the Share button (in the new window, you will see the Id number).

YouTube embed video

Note: By pressing the button Share you can use the option Embed <> to get ready code which you can paste into your HTML document, however, if you want to set your own settings (like dimension, autoplay, loop, etc…) and learn how to write the code by yourself follow the steps below.

By using the height and width attributes you can define the dimension of the player:

<!DOCTYPE html>
<html>
<body>

<iframe width="100%" height="400" src="https://www.youtube.com/embed/o5daeOwl-4Q">
</iframe>

</body>
</html>

Output:

An <iframe> with a specified width of 100% and a height of 400px:

You can let your video start playing automatically when a user visits your website, by adding autoplay=1 to the YouTube URL. Automatically starting video can be annoying for your website visitors so you can set the muted autoplay by adding mute=1 after autoplay=1 to let your video start playing automatically (but muted):

<!DOCTYPE html>
<html>
<body>

<iframe width="100%" height="400" src="https://www.youtube.com/embed/o5daeOwl-4Q?autoplay=1&mute=1">
</iframe>

</body>
</html>

Output:

The video will play once when the value is set to 0 (default), with the value 1 the video will loop (forever). Add loop=1 to let your video loop forever:

<!DOCTYPE html>
<html>
<body>

<iframe width="100%" height="345" src="https://www.youtube.com/embed/o5daeOwl-4Q?loop=1">
</iframe>

</body>
</html>

Output:

To not display controls in the video player set the controls=0, to display the controls in the video player set the controls=1 (default):

<!DOCTYPE html>
<html>
<body>

<iframe width="100%" height="345" src="https://www.youtube.com/embed/o5daeOwl-4Q?controls=0">
</iframe>

</body>
</html>

Output:

Enjoy coding!