0
0
HtmlHow-ToBeginner · 3 min read

How to Embed YouTube Video in HTML Easily

To embed a YouTube video in HTML, use the <iframe> tag with the video's URL in the src attribute. Set width, height, and allowfullscreen for best viewing experience.
📐

Syntax

The basic syntax to embed a YouTube video uses the <iframe> tag. The src attribute holds the video URL. You can set width and height to control the size. The allowfullscreen attribute lets users watch the video in fullscreen mode.

html
<iframe width="560" height="315" src="https://www.youtube.com/embed/VIDEO_ID" title="YouTube video player" frameborder="0" allowfullscreen></iframe>
Output
A rectangular video player area where the YouTube video will play.
💻

Example

This example shows how to embed a YouTube video with a specific video ID. Replace VIDEO_ID with the actual ID from the YouTube video URL.

html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Embed YouTube Video Example</title>
</head>
<body>
  <h1>My Favorite Video</h1>
  <iframe width="560" height="315" src="https://www.youtube.com/embed/dQw4w9WgXcQ" title="YouTube video player" frameborder="0" allowfullscreen></iframe>
</body>
</html>
Output
A webpage with a heading 'My Favorite Video' and a YouTube video player showing the video with ID dQw4w9WgXcQ.
⚠️

Common Pitfalls

  • Using the full YouTube watch URL (like https://www.youtube.com/watch?v=VIDEO_ID) instead of the embed URL (https://www.youtube.com/embed/VIDEO_ID) will not work.
  • Forgetting to add allowfullscreen prevents fullscreen mode.
  • Not setting width and height can cause the video to appear too small or too large.
html
<!-- Wrong way: Using watch URL -->
<iframe src="https://www.youtube.com/watch?v=dQw4w9WgXcQ"></iframe>

<!-- Right way: Using embed URL -->
<iframe src="https://www.youtube.com/embed/dQw4w9WgXcQ" allowfullscreen></iframe>
Output
The first iframe will not display the video correctly; the second iframe will show the video with fullscreen enabled.
📊

Quick Reference

Remember these tips when embedding YouTube videos:

  • Use https://www.youtube.com/embed/VIDEO_ID as the src.
  • Set width and height for proper size.
  • Add allowfullscreen to enable fullscreen mode.
  • Include title for accessibility.

Key Takeaways

Use the