YouTube video can be embedded in a web page using either an <iframe> tag or an <object> tag. IFrame embeds are the recommended method for embedding a YouTube video because the IFrame will select the appropriate player based on the client's capabilities and available YouTube file formats. Sample of a YouTube video's <iframe> tag for IFrame embeds is shown below:
<iframe width="560" height="315" src="https://www.youtube.com/embed/iVAgTiBrrDA" frameborder="0" allowfullscreen></iframe>
The URL has the following format:
https://www.youtube.com/embed/VIDEO_ID
Optionally, you can append parameters directly to the end of the URL like the following.
https://www.youtube.com/embed/iVAgTiBrrDA?autohide=1&rel=0&showinfo=0
IFrame embeds come with a fixed size by default. Since multiple screen sizes support is important nowadays, we may want the embedded video to be responsive, which means allow browsers to determine video dimensions based on the width of their containing block by creating an intrinsic ratio that will properly scale on any device.
To responsive embed a YouTube video, we need to wrap the <iframe>
in a <div>
container and apply some CSS code. Then remove width
and height
attributes in the <iframe>
. You also don't need to include frameborder="0"
in your <iframe>
as the CSS code overrides that for you.
HTML
<div class="video-container"> <iframe src="https://www.youtube.com/embed/iVAgTiBrrDA" allowfullscreen></iframe> </div>
CSS
.video-container { position: relative; display: block; height: 0; padding-top: 30px; padding-bottom: 56.25%; overflow: hidden; } .video-container iframe { position: absolute; top: 0; bottom: 0; left: 0; width: 100%; height: 100%; border: 0; }
Demo
Below is a sample of responsive embedded YouTube video.