Embedding a YouTube Video
To embed a YouTube video in an HTML document, use the iframe element. This element allows you to insert content from another website (in this case, YouTube's video player) directly onto your page.
Embedding a video from YouTube is often better than hosting the video yourself, as it saves bandwidth and ensures that your video is compressed and served efficiently by YouTube's servers.
The YouTube Embed Code
YouTube actually provides the code for you. Simply find the video on YouTube, click the Share button, and then choose Embed. You'll see a snippet of code like this:
Key Attributes
src: This is the URL of the video's embed page (note that it uses/embed/rather than the standard watch URL).widthandheight: These set the dimensions of the video player on your page.allowfullscreen: This allows the user to expand the video to fill their entire screen.referrerpolicy: This attribute specifies the referrer policy for the request.allow: This attribute specifies which features (like autoplay or picture-in-picture) are permitted within the frame.
Example
Below is a working example of an embedded YouTube video:
Responsive YouTube Embeds
By default, if you specify fixed width and height attributes, the video player will not be responsive. It will remain the same size even if your page is viewed on a small screen, potentially causing layout issues.
To make a YouTube embed responsive, you can wrap the iframe in a container and use CSS to maintain the 16:9 aspect ratio as it scales:
Here it is in a live example where you can resize your browser window to see the effect:
A Note on Cookies
In the YouTube embed window, there is an option for "Enable privacy-enhanced mode." Selecting this will change the URL to use youtube-nocookie.com, which prevents YouTube from storing information about your visitors unless they actually play the video.