HTML <iframe> tag
The <iframe>
tag in HTML is used to embed another HTML document within the current document. It creates an inline frame that can display a separate web page or content from a different source. The embedded content is treated as a separate browsing context, allowing for the inclusion of external resources or applications.
Syntax:
<iframe src="https://www.example.com" width="600" height="400" frameborder="0">
<!-- Fallback content if the iframe is not supported -->
</iframe>
Key Attributes:
src
:- Specifies the URL of the document to embed in the iframe.
<iframe src="https://www.example.com"></iframe>
width
andheight
:- Define the dimensions of the iframe in pixels.
<iframe src="https://www.example.com" width="800" height="600"></iframe>
frameborder
:- Specifies whether or not to display a border around the iframe. It is deprecated in HTML5 and should be replaced with CSS for styling.
<iframe src="https://www.example.com" frameborder="0"></iframe>
allow
:- Provides permissions for certain features such as microphone, camera, fullscreen, and more. It enhances security and privacy by specifying what the embedded content is allowed to do.
<iframe src="https://www.example.com" allow="fullscreen; microphone"></iframe>
sandbox
:- Enables a set of restrictions on the iframe's content, such as disabling scripts or forms. It can take a list of values to apply specific restrictions.
<iframe src="https://www.example.com" sandbox="allow-scripts"></iframe>
title
:- Provides a title for the iframe content, which can be useful for accessibility purposes.
<iframe src="https://www.example.com" title="Example Site"></iframe>
Example Usage:
Basic Example:
<iframe src="https://www.example.com" width="600" height="400"></iframe>
In this example, the iframe embeds the content from "https://www.example.com" with a width of 600 pixels and a height of 400 pixels.
Example with Attributes:
<iframe src="https://www.example.com" width="800" height="600" frameborder="0" allow="fullscreen" title="Example Site"></iframe>
In this example:
- The iframe displays content from "https://www.example.com".
- It has no border (
frameborder="0"
). - It allows fullscreen mode.
- The
title
attribute provides a description for accessibility.
Accessibility and Security Considerations:
Accessibility: Providing a meaningful
title
attribute helps users who rely on screen readers understand the purpose of the iframe. Ensure that the content inside the iframe is accessible and usable.Security: Using the
sandbox
attribute helps restrict what the iframe content can do, enhancing security. For example,sandbox="allow-scripts"
allows scripts but prevents other actions such as form submissions or navigation. Be cautious with theallow
attribute to ensure that only the necessary permissions are granted.