Embedding Content in HTML

Embed YouTube videos, maps, PDFs and other content safely and responsively with iframe, object and embed, using privacy-friendly and fast-loading techniques.

Lesson 29 of 44Intermediate25 min read

Videos, maps, social posts, slides and documents often live on another service, and the easiest way to show them on your page is to embed them. You've already seen the basics in the iframes lesson; this lesson focuses on the embeds people actually ask about most: YouTube videos, maps and PDF documents, and on doing it the right way for speed, privacy and phones.

Embeds are heavy. A single YouTube player can download over a megabyte of scripts before anyone presses play, and a map loads dozens of images. Done carelessly, a few embeds make a page slow, jump around as they load, and overflow narrow screens. Done well, they load only when needed, keep a fixed shape, and scale to any screen width.

You'll also meet the <object> and <embed> elements, which display files such as PDFs directly, and learn what to show as a fallback when a browser or a privacy setting blocks the content.

Embedding a YouTube video

Start on the video's YouTube page and choose Share, then Embed. Copy the supplied iframe code rather than the address from your browser. The short link used for sharing and the normal watch page open YouTube's website; the embed address opens a player designed to sit inside another page. You do not need an API key for this basic HTML YouTube embed.

The video ID identifies the recording. In the address below, replace VIDEO_ID with the ID from your chosen video. Keep the HTTPS scheme, the hostname and the /embed/ path. A public video can still have embedding disabled by its owner, so check the finished player on your website as well as on YouTube.

HTML
<iframe
  src="https://www.youtube-nocookie.com/embed/VIDEO_ID"
  title="How to make sourdough bread"
  loading="lazy"
  allow="accelerometer; encrypted-media; gyroscope; picture-in-picture; fullscreen"
  referrerpolicy="strict-origin-when-cross-origin"
  allowfullscreen>
</iframe>
  • Use the embed URL (/embed/VIDEO_ID), not the normal watch page URL.
  • The youtube-nocookie.com domain enables YouTube's privacy-enhanced mode, which limits how embedded views are used for personalization. It still connects to YouTube when the player loads.
  • Add ?start=90 to start at 1 minute 30 seconds, or ?rel=0 to show related videos from the same channel only.
  • loading="lazy" delays the whole player until it's scrolled near.

Use a title that describes the video, such as "HTML crash course for beginners", rather than "iframe" or "YouTube". The title names the frame for assistive technology; it does not add a visible heading or replace captions. Introduce the video in the surrounding text so readers understand why watching it will help.

When adding several player options, start the query string with ? and separate subsequent options with &amp; in HTML. For instance, ?start=90&amp;rel=0 combines a starting position with the related-video setting. That setting does not remove related videos entirely. Check the official YouTube player parameters before relying on an option from an older tutorial.

Responsive embeds

Embed codes come with fixed width and height attributes, which overflow on phones. Make them fluid with CSS:

CSS
.video {
  width: 100%;
  aspect-ratio: 16 / 9;
  height: auto;
  border: 0;
}

aspect-ratio keeps the frame's shape as the width changes and reserves the right amount of space before it loads, so the page doesn't jump. Older tutorials use a "padding-top: 56.25%" wrapper to do the same thing; aspect-ratio replaces that trick.

An iframe is its own document, so your page's CSS controls the outer frame rather than the video controls or map labels inside it. object-fit: cover will not resize a third-party player's contents the way it resizes an image. Adjust the iframe's width and height, then let the provider arrange its own interface.

Remember height: auto when using an aspect ratio. A definite height can prevent the ratio from producing the shape you intended. A map often needs more vertical space than a widescreen video because visitors must read street names and use zoom controls. The map example uses a 4:3 shape for that reason. Test the frame inside your actual content column, including any padding, rather than assuming that a desktop-sized preview proves it fits a phone.

Maps, PDFs, object and embed

  • Maps: Google Maps (Share, then Embed a map) and OpenStreetMap (Share, then HTML) both give iframe code. Add a title and loading="lazy", and also include the address as text so it's readable without the map.
  • PDFs: the simplest option is a link, <a href="menu.pdf">Download our menu (PDF, 2 MB)</a>. To show it inside the page, use <object data="menu.pdf" type="application/pdf"> with a link inside as the fallback, or an <iframe>. Many phones won't display embedded PDFs, so always offer the link.
  • <embed> is a simpler, older element with no fallback content. Prefer <object> or <iframe>.

Choose the element according to what you are displaying. An iframe suits a hosted application, including a YouTube player, an interactive map or a slide viewer. An object can display a document and contains fallback HTML if the browser cannot render that resource. The embed element is a void element, so it has no closing tag and cannot contain a fallback paragraph. For a video file you host yourself, the native <video> element is usually a better starting point; see HTML media.

Adding a useful map to a contact page

An embedded map should help someone reach a specific place. Write the street address beside it, explain which entrance to use when that matters, and provide a link that opens the location in a full map. People may need to copy the address into a navigation app, and a text address remains available when the interactive view cannot load.

For Google Maps, find the destination first and use Share, then Embed a map. The regular sharing link and the iframe source are different addresses. OpenStreetMap also provides an HTML embed through its sharing tools. Keep the provider's attribution visible, and check that the frame shows the intended neighbourhood at a useful zoom level.

The address in this lesson is sample shop content. When adapting the example, update the address, iframe title, map destination and larger-map link together. Coordinates normally use latitude followed by longitude in map links; other formats, such as an OpenStreetMap bounding box, have their own ordering. Copying a provider-generated embed avoids many coordinate mistakes. A map is an illustration of the location, while the written address supplies the contact information readers can actually use.

Embedding a PDF with a dependable fallback

Before adding a PDF viewer, ask whether visitors need the document inside the page. A short menu, price list or set of instructions may be easier to read as HTML, especially on a phone. A download link is useful when the original document needs to be saved or printed. An embedded PDF makes sense when readers benefit from previewing a longer document without leaving the surrounding explanation.

Use a descriptive link that names the document and identifies it as a PDF. Include the file size when you know it and keep that label accurate after replacing the file. Relative paths such as guide.pdf resolve against the page's location, so a document stored elsewhere needs the corresponding path. A missing file or a server that forces downloads can stop an inline preview from appearing.

Content inside <object> is a fallback, but a PDF viewer can sometimes open and still be awkward to use. Place an additional download link outside the viewer when access to the document matters. An iframe does not display its child HTML as a PDF fallback, so its alternative link must be outside it. The MDN iframe reference explains this distinction. Test the actual PDF on a phone as well as on a desktop browser.

Lazy loading, facades and visitor privacy

Lazy loading and a video facade solve different problems. loading="lazy" lets the browser postpone an iframe until it approaches the visible area. The browser can still fetch it before the visitor interacts with it. A facade waits for a deliberate action, which is useful on a page containing several videos that most readers will never play.

The facade example uses a real button, so keyboard users can activate it with Enter or Space. Its accessible name describes the action and the video. JavaScript creates a native video player only after activation, then replaces the button and requests playback. The browser can still refuse that request, so keep the player's normal controls available for manual playback. A hosted iframe player can use the same facade pattern, but needs the provider's embed address and appropriate playback permissions.

Privacy-enhanced mode reduces personalization; it does not mean the player makes no network requests or that every privacy requirement is automatically satisfied. A remote thumbnail also contacts its image host before playback. Use a locally hosted image or a CSS placeholder when that initial connection is unnecessary. YouTube describes the current behaviour in its embedding and privacy-enhanced mode guidance.

Choosing a free sample video

Use a sample with clear reuse terms when demonstrating video playback. The live examples combine an ocean photograph by Jeremy Bishop from Unsplash with a short coastal video by ArtHouse Studio from Pexels. Unsplash supplies the still cover image displayed before playback; the MP4 comes from Pexels. Check the Unsplash image license and Pexels video license when selecting your own assets. Both examples keep the source credits beside the player.

A direct MP4 belongs in a native <video> element; a YouTube embed belongs in an iframe. Both can be responsive, and both can load after a button click. For the native player, preload="none" asks the browser to avoid fetching video data in advance, while the poster supplies an initial image. This differs from an iframe's loading="lazy" attribute. The YouTube syntax in this lesson uses VIDEO_ID placeholders so you can supply your own recording when needed.

Why an embedded video or map may not load

First separate a broken address from a blocked embed. Check the resource on the provider's normal website. If it is missing there too, the video may have been deleted or the document moved. If it works there but fails inside your page, check whether the provider allows embedding and whether you copied its embed URL. Many websites deliberately refuse to appear inside another site's iframe.

A YouTube embed URL is designed to load inside a webpage. Pasting it directly into the browser address bar is not a reliable playback test. YouTube requires referrer information and can show error 153 when it is absent. Keep referrerpolicy="strict-origin-when-cross-origin" on the iframe and test from a page served over HTTP or HTTPS. A local file, a restrictive preview sandbox or a privacy extension may behave differently from your hosted page. The YouTube player error reference distinguishes missing-referrer errors from unavailable videos and disabled embedding.

Next inspect the browser console and Network panel. A content security policy may reject the frame's hostname, an HTTP resource may be blocked on an HTTPS page, or the provider may return an error. A map can also fail because its scripts or tiles are unavailable. Making the iframe taller fixes clipping, but it cannot fix a network refusal. Preserve the address and external link so visitors still have a useful next step while you investigate.

Accessible embedding and a final publishing check

Give each iframe a specific title and keep useful context outside it. A title helps readers identify the embedded document, while a nearby heading explains its role in the page. For a teaching video, provide a written explanation and choose a recording with captions. For a map, include the destination in text. For a PDF, consider an HTML version when the information is essential to completing a task.

Before publishing, use the page at a narrow width, navigate through the controls with the keyboard, and activate the facade once. Check that the player replaces the button without stretching the layout and that links lead to the expected video, address or document. Temporarily block the external service to see whether the surrounding content still makes sense. These checks help you deliver a useful HTML embed even when a visitor cannot access the third-party content.

HTML Embedding Syntax

Embed patterns

<iframe class="video" src="https://www.youtube-nocookie.com/embed/ID?start=30" title="Video title" loading="lazy" allowfullscreen></iframe>
<iframe src="MAP_EMBED_URL" title="Map of our shop" loading="lazy"></iframe>
<object data="guide.pdf" type="application/pdf" width="100%" height="500">
  <a href="guide.pdf">Download the guide (PDF)</a>
</object>
.video { width: 100%; height: auto; aspect-ratio: 16 / 9; border: 0; }

HTML Embedding Summary

  • Embed YouTube with its /embed/ URL; youtube-nocookie.com improves privacy.
  • Always add a title and loading="lazy" to embedded frames.
  • Use width: 100% and aspect-ratio to make embeds responsive without layout jumps.
  • Give PDFs and maps a plain link or text address as a fallback.
  • Prefer <object> or <iframe> over <embed>, which has no fallback.

HTML Embedding Examples

Each example runs in the page. Edit the code and press Run to see what changes.

Example 1

A responsive video

A responsive player with an Unsplash cover image, native video controls and source credits. The video data loads when the visitor starts playback.

<style>
  .media-demo { width: 100%; max-width: 560px; margin: 0; font-family: system-ui, sans-serif; }
  .video { display: block; width: 100%; height: auto; aspect-ratio: 16 / 9; border-radius: 12px; background: #0f172a; }
  .media-demo figcaption { margin-top: 12px; color: #475569; font-size: 13px; line-height: 1.7; }
  .media-demo strong { display: block; color: #0f172a; font-size: 16px; }
  .media-demo a { color: #0f766e; text-underline-offset: 3px; }
</style>
<figure class="media-demo">
  <video class="video" controls playsinline preload="none"
    poster="https://images.unsplash.com/photo-1465982046896-5172ca240f27?auto=format&amp;fit=crop&amp;w=1120&amp;h=630&amp;q=80"
    aria-label="Ocean in motion: aerial coastal footage">
    <source src="https://videos.pexels.com/video-files/4631568/4631568-hd_1280_720_24fps.mp4" type="video/mp4">
    <a href="https://videos.pexels.com/video-files/4631568/4631568-hd_1280_720_24fps.mp4">Open the video (MP4)</a>.
  </video>
  <figcaption>
    <strong>Ocean in motion</strong>
    Cover: <a href="https://unsplash.com/photos/C-opW0i5McE">Jeremy Bishop / Unsplash</a> &middot; Video: <a href="https://www.pexels.com/video/aerial-view-of-ocean-waves-4631568/">ArtHouse Studio / Pexels</a>.
    <br><a href="https://videos.pexels.com/video-files/4631568/4631568-hd_1280_720_24fps.mp4">Open video (MP4)</a>
  </figcaption>
</figure>
ResultEdit the code, then press Run or Ctrl+Enter
Line-by-line explanation
  1. Lines 2 to 3The figure fits its container and the video keeps a 16:9 display area with rounded corners.
  2. Lines 9 to 11Native controls, inline playback and an Unsplash poster introduce the video without downloading it first.
  3. Lines 12 to 13A 720p MP4 stock clip with a fallback link for browsers that cannot display HTML video.
  4. Lines 15 to 19A semantic caption names the clip, credits the image and video separately, and provides a direct video link.
Example 2

A map with a text address

<style>.map { width: 100%; max-width: 480px; height: auto; aspect-ratio: 4 / 3; border: 0; }</style>
<h3>Visit our shop</h3>
<address>12 Market Street, Leeds LS1 6DT</address>
<iframe class="map"
  src="https://www.google.com/maps?q=Market%20Street%2C%20Leeds%2C%20UK&amp;z=16&amp;output=embed"
  title="Map showing our shop on Market Street, Leeds"
  loading="lazy" referrerpolicy="strict-origin-when-cross-origin"></iframe>
<p><a href="https://www.google.com/maps/search/?api=1&amp;query=Market%20Street%2C%20Leeds%2C%20UK">Open a larger map</a></p>
ResultEdit the code, then press Run or Ctrl+Enter
Line-by-line explanation
  1. Line 3The address is real text, readable even if the map doesn't load.
  2. Line 5A Google Maps embed of Market Street in Leeds; update it together with the sample address for your own shop.
  3. Lines 6 to 7Title and lazy loading, as for any iframe.
  4. Line 8A link to a full-size map is handy on phones.
Example 3

A video facade that loads on click

<style>
  .media-demo { width: 100%; max-width: 560px; margin: 0; font-family: system-ui, sans-serif; }
  .facade { position: relative; display: grid; place-items: center; width: 100%; aspect-ratio: 16 / 9; padding: 0; border: 0; border-radius: 12px; cursor: pointer; color: #fff; background: linear-gradient(180deg, rgb(15 23 42 / 10%), rgb(15 23 42 / 65%)), center / cover url('https://images.unsplash.com/photo-1465982046896-5172ca240f27?auto=format&fit=crop&w=1120&h=630&q=80'); }
  .facade:focus-visible { outline: 3px solid #0d9488; outline-offset: 4px; }
  .facade-play { display: grid; place-items: center; width: 60px; height: 60px; border-radius: 50%; background: #fff; color: #0f172a; font-size: 22px; box-shadow: 0 8px 24px rgb(0 0 0 / 18%); }
  .facade-label { position: absolute; left: 20px; bottom: 18px; text-align: left; font-size: 16px; font-weight: 600; }
  .facade-label small { display: block; margin-top: 4px; color: #e2e8f0; font-size: 12px; font-weight: 400; }
  .player { display: block; width: 100%; height: auto; aspect-ratio: 16 / 9; border-radius: 12px; background: #0f172a; }
  .media-demo figcaption { margin-top: 12px; color: #475569; font-size: 13px; line-height: 1.7; }
  .media-demo a { color: #0f766e; text-underline-offset: 3px; }
  .playback-status { color: #475569; font: 14px/1.5 system-ui, sans-serif; }
</style>
<figure class="media-demo">
  <button class="facade" type="button" aria-label="Play Ocean in motion">
    <span class="facade-play" aria-hidden="true">&#9654;</span>
    <span class="facade-label" aria-hidden="true">Ocean in motion<small>Coastal stock footage &middot; Click to play</small></span>
  </button>
  <figcaption>
    Cover: <a href="https://unsplash.com/photos/C-opW0i5McE">Jeremy Bishop / Unsplash</a> &middot; Video: <a href="https://www.pexels.com/video/aerial-view-of-ocean-waves-4631568/">ArtHouse Studio / Pexels</a>.
    <br><a href="https://videos.pexels.com/video-files/4631568/4631568-hd_1280_720_24fps.mp4">Open video (MP4)</a>
  </figcaption>
</figure>
<p class="playback-status" role="status"></p>
<script>
  document.querySelector('.facade').addEventListener('click', (e) => {
    const player = document.createElement('video');
    player.className = 'player';
    player.controls = true;
    player.playsInline = true;
    player.tabIndex = 0;
    player.setAttribute('aria-label', 'Ocean in motion: aerial coastal footage');
    player.poster = 'https://images.unsplash.com/photo-1465982046896-5172ca240f27?auto=format&fit=crop&w=1120&h=630&q=80';
    player.src = 'https://videos.pexels.com/video-files/4631568/4631568-hd_1280_720_24fps.mp4';
    e.currentTarget.replaceWith(player);
    player.focus();
    player.play().catch(() => {
      document.querySelector('.playback-status').textContent = 'Use the video controls to start playback.';
    });
  });
</script>
ResultEdit the code, then press Run or Ctrl+Enter
Line-by-line explanation
  1. Lines 2 to 11A responsive cover, a clear play button, readable caption styles and a visible keyboard focus outline.
  2. Lines 14 to 17The real button supports mouse, touch, Enter and Space; its accessible name describes the action.
  3. Lines 18 to 23The image and video credits stay visible, with a direct link and a playback status message.
  4. Lines 25 to 35Clicking creates the video, adds its source and controls, then moves keyboard focus to the player.
  5. Lines 36 to 38Playback starts after the click; a status message helps if the browser requires another action.

Common HTML Embedding Mistakes

Using the watch URL

Don't
<iframe src="https://www.youtube.com/watch?v=VIDEO_ID"></iframe>
Do
<iframe src="https://www.youtube-nocookie.com/embed/VIDEO_ID" title="Video: your chosen sample" referrerpolicy="strict-origin-when-cross-origin"></iframe>

The normal page refuses to load inside a frame.

Fixed-size embeds on phones

Don't
<iframe width="900" height="500" src="..."></iframe>
Do
<iframe style="width: 100%; height: auto; aspect-ratio: 16 / 9;" src="..." title="..."></iframe>

A 900px frame forces sideways scrolling on a 390px phone.

A PDF with no fallback

Don't
<embed src="menu.pdf" width="600" height="800">
Do
<object data="menu.pdf" type="application/pdf" width="100%" height="600">
  <a href="menu.pdf">Download the menu (PDF, 1.2 MB)</a>
</object>

Some browsers cannot show embedded PDFs; a direct link gives visitors another way to open the document.

HTML Embedding in Real Projects

Embeds on real sites

Restaurants embed maps and PDF menus, schools embed lesson videos, and product pages embed demo videos. Fast sites such as news publishers use click-to-load facades for every third-party player, and privacy laws in many countries push sites towards youtube-nocookie embeds and consent before loading tracking content.

HTML Embedding Exercises

Answer each one and check it instantly. If you get stuck, open the hint before the answer.

Fill in the blankseasy

Make the video frame load only when it's near the viewport.

<iframe src="https://www.youtube-nocookie.com/embed/abc" title="Demo" loading=""></iframe>
Multiple choiceeasy

Which YouTube address should go in an iframe's src?

Multiple choicemedium

Which CSS property keeps an embed's shape as its width changes?

Multiple choicemedium

Why add a download link inside an <object> showing a PDF?

Fix the bugmedium

Fix this embed: use the embed URL on youtube-nocookie.com (video id abc123), add a title, lazy loading, and make it responsive with the .video class.

<style>.video { width: 100%; aspect-ratio: 16 / 9; border: 0; }</style>
<iframe src="https://www.youtube.com/watch?v=abc123" width="900" height="500"></iframe>
ResultEdit the code, then press Run or Ctrl+Enter
Checks
  • Uses the nocookie embed URL
  • Has a title
  • Lazy loaded
  • Uses the responsive class

HTML Embedding Quiz

5 questions to check what you learned.

  1. What does youtube-nocookie.com do?

    • Removes adverts
    • Makes videos load faster
    • Hides the YouTube logo
    • Avoids setting tracking cookies until the video is played
  2. How do you start an embedded YouTube video at 2 minutes?

    • ?time=2m
    • ?start=120
    • #120
    • ?seek=2
  3. Why include the address as text next to an embedded map?

    • Maps require it
    • To improve map accuracy
    • So it's readable if the map doesn't load and for screen-reader and search engine users
    • It isn't useful
  4. What is a facade for an embedded video?

    • A lightweight thumbnail and play button that loads the real player only on click
    • A fake video
    • A video filter
    • A CSS animation
  5. Why is <embed> usually avoided for PDFs?

    • It's not valid HTML
    • It only works with images
    • It has no fallback content, so nothing helpful shows when the PDF can't be displayed
    • It requires JavaScript

HTML Embedding Challenge

A responsive tutorial embed

Create:

  1. A <style> rule for .embed with width: 100% and aspect-ratio: 16 / 9
  2. An iframe with class embed, a youtube-nocookie embed URL, a title and loading="lazy"
  3. A paragraph with a text link to the same topic, as an alternative
ResultEdit the code, then press Run or Ctrl+Enter
Checks
  • The embed is full width with a 16:9 ratio
  • Uses a nocookie embed URL
  • Has a title and lazy loading
  • A text link alternative