The HTML <iframe>
tag is used to embed a webpage within a webpage. It is also called an inline frame. For example,
<iframe src="https://codingmaster.pro" title="codemy pro website" height="500" width="500" ></iframe>
Browser Output
Here,
src
: It is used to specify the URL of the website to be loaded.title
: It is good practice to include a title attribute so that screen readers can read the title to users.
Other Attributes for <iframe>
There are some importat attributes for <iframe>
. They are:
- height and width
- name
- srcdoc
We will explore each of them in detail.
height and width
We can set the height and width of the <iframe>
element with the height
or width
attribute. For example,
<iframe src="https://codingmaster.pro" height="200" width="300"></iframe>
We can also use CSS to set the width and height of the <iframe>
using the style
attribute. For example,
<iframe src="https://codingmaster.pro" style="height:200px;width:300px"></iframe>
It is important to add height and width to allocate space on the webpage for the iframe. It prevents content from moving when the iframe loads.
name
The name
attribute is used to specify the name for an iframe. It can be used as a target for other HTML elements like the <a>
tag. For example,
<iframe src="https://parewalabs.com" name="iframe_target" height="500" width="400"></iframe>
<a href="https://www.codingmaster.pro" target="iframe_target">Switch to codemy Pro</a>
Browser Output (Before Clicking the link)
Browser Output (After clicking the link)
Here, clicking the <a>
tag changes the URL of the target instead of the current window.
srcdoc
Instead of a website URL, we can send HTML directly to the iframe, which will be displayed instead of another website. For example,
<iframe srcdoc="<h1>Learn to code</h1>"></iframe>
Browser Output