SmartCodingTips

Using the HTML <iframe> Tag

The <iframe> tag allows you to embed another HTML page within the current page. It is commonly used for embedding videos, maps, or other external content.

Basic iFrame Example

Embedding an external webpage or content inside an iframe:


<iframe src="https://www.example.com" width="600" height="400" title="Example Site">
  Your browser does not support iframes.
</iframe>
            

Common Attributes of <iframe>

  • src: URL of the page to embed.
  • width and height: Dimensions of the iframe in pixels.
  • title: Descriptive text for accessibility.
  • frameborder: Specifies the border thickness (deprecated, use CSS instead).
  • allowfullscreen: Enables fullscreen mode for embedded videos.
  • loading: Controls lazy loading with values like lazy or eager.
  • sandbox: Applies extra restrictions to the content inside the iframe for security.

Using Sandbox Attribute

The sandbox attribute restricts actions inside the iframe, improving security. You can allow specific features by listing tokens:


<iframe src="page.html" sandbox="allow-scripts allow-same-origin"></iframe>
            

Without allow-scripts or allow-same-origin, scripts and cookies are blocked inside the iframe.

Responsive iFrames

To make iframes responsive, use CSS techniques like aspect-ratio boxes or utility classes:


.responsive-iframe {
  position: relative;
  width: 100%;
  padding-bottom: 56.25%; /* 16:9 Aspect Ratio */
  height: 0;
  overflow: hidden;
}

.responsive-iframe iframe {
  position: absolute;
  top: 0; left: 0;
  width: 100%;
  height: 100%;
  border: 0;
}
            

Accessibility Tips

  • Always include a meaningful title attribute to describe the iframe content.
  • Provide fallback text between the opening and closing tags for browsers that do not support iframes.
  • Use the sandbox attribute to limit potential security risks.