How to Use iframe in HTML: Syntax, Example, and Tips
Use the
<iframe> tag in HTML to embed another webpage inside your current page. Set the src attribute to the URL you want to show, and optionally control size with width and height.Syntax
The <iframe> tag creates an inline frame to embed another HTML page inside the current page. The main attribute is src, which specifies the URL of the page to display. You can also set width and height to control the frame size. The title attribute improves accessibility by describing the iframe content.
html
<iframe src="URL" width="WIDTH" height="HEIGHT" title="DESCRIPTION"></iframe>
Example
This example shows how to embed the Wikipedia homepage inside your page using an iframe. It sets the width to 600 pixels and height to 400 pixels, and includes a title for accessibility.
html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>iframe Example</title> </head> <body> <h1>Embedding Wikipedia with iframe</h1> <iframe src="https://www.wikipedia.org" width="600" height="400" title="Wikipedia Homepage"></iframe> </body> </html>
Output
A webpage with a heading 'Embedding Wikipedia with iframe' and below it a rectangular area showing the Wikipedia homepage inside the page.
Common Pitfalls
- Not setting the
titleattribute can make the iframe inaccessible to screen readers. - Using fixed pixel sizes without responsive design can cause layout issues on small screens.
- Some websites block being loaded in iframes for security reasons (using X-Frame-Options), so the iframe may appear blank or show an error.
- Not specifying
widthandheightcan cause the iframe to be very small or default size.
html
<!-- Wrong: Missing title and size --> <iframe src="https://example.com"></iframe> <!-- Right: With title and size --> <iframe src="https://example.com" width="800" height="600" title="Example Site"></iframe>
Quick Reference
Attributes for <iframe>:
src: URL of the page to embed (required)width: Width of the iframe (e.g., "600" or "100%")height: Height of the iframe (e.g., "400")title: Description for accessibility (important)loading: "lazy" to defer loading offscreen iframesallowfullscreen: Allow fullscreen mode if supported
Key Takeaways
Use
Always include a descriptive title attribute for accessibility.
Set width and height to control the iframe size and improve layout.
Some sites block iframe embedding for security, so test your URLs.
Use loading="lazy" to improve page load performance for offscreen iframes.