How does the <iframe> tag work and what is it used for?

MediumIntermediateHtml
Quick Answer

The <iframe> element creates a nested browsing context, so the real production concerns are sandboxing, performance, accessibility, and third-party embed pitfalls.

Answer

Overview

The iframe tag creates a separate browsing context inside your page. In production, the key question is not just whether an embed works, but what permissions, loading cost, accessibility impact, and security risk that third-party content brings with it.

Attribute

Purpose

Example Value

src

Specifies the URL of the page to display

src="https://example.com"

width / height

Define frame dimensions

width="600" height="400"

title

Provides an accessible name for screen readers

title="Embedded map"

allowfullscreen

Lets embedded videos enter fullscreen mode

allowfullscreen

loading

Controls loading behavior for performance

loading="lazy"

Common attributes of the <iframe> element

Basic Example

HTML
<iframe src="https://www.example.com" width="600" height="400" title="Example Website"></iframe>
                  

This code embeds the page at https://www.example.com directly inside your webpage.

Example: Embedding a YouTube Video

HTML
<iframe width="560" height="315" src="https://www.youtube.com/embed/dQw4w9WgXcQ" title="YouTube video player" frameborder="0" allowfullscreen></iframe>
                  

The YouTube video is displayed inside the frame, allowing playback without leaving your site.

Security and Best Practices

  • Always specify the title attribute for accessibility.
  • Use the sandbox attribute to restrict what embedded content can do (e.g., prevent scripts or forms).
  • Only embed trusted sources — malicious sites could attempt cross-site scripting (XSS) attacks.
  • Use loading="lazy" to improve performance by deferring off-screen iframes.

Sandbox Example

You can limit iframe permissions using the sandbox attribute:

HTML
<iframe src="/docs/guide.html" sandbox></iframe>
<!-- Disables scripts, forms, and same-origin access -->
                  
Still so complicated?

Think of an iframe as a window inside your page — it shows another page, but you can decide how much control that page has through attributes like sandbox or allowfullscreen.

Summary
  • iframe embeds one webpage into another.
  • Commonly used for videos, maps, or third-party content.
  • Supports attributes like src, title, sandbox, and allowfullscreen.
  • Use it responsibly to avoid performance or security issues.
Similar questions
Guides
Preparing for interviews?

Use the relevant interview-question hub first, then move into a concrete study plan before targeted company sets.