HTML Frames

HTML frames allow you to display multiple HTML documents within a single browser window. In modern web development, this is typically achieved using the <iframe> tag.

Note: Traditional frame technology using <frameset> and <frame> tags has been deprecated in HTML5. They have many usability, accessibility, and SEO issues and should no longer be used. This chapter will focus on the modern <iframe>.

<iframe> - Inline Frame

The <iframe> (Inline Frame) tag is used to embed another independent HTML document within the current HTML document. It creates a rectangular area that can display content from different sources.

This is very useful for embedding third-party content, such as:

  • Online videos (like YouTube, Vimeo)
  • Interactive maps (like Google Maps)
  • Social media posts
  • Advertising banners

Example:

<iframe src="https://www.example.com" title="Example Website">
</iframe>

The src Attribute

The src attribute specifies the URL of the page to embed. This is the most core attribute of <iframe>.

The width and height Attributes

You can use the width and height attributes to specify the dimensions of the <iframe> (in pixels or percentages).

<iframe src="demo_iframe.htm" height="200" width="300" title="Iframe Example"></iframe>

You can also use CSS to control its dimensions, which is more recommended for responsive design.

iframe {
  width: 100%;
  height: 400px;
  border: none; /* Remove default border */
}

The title Attribute

Providing a title attribute for <iframe> is crucial for accessibility. Screen readers will read this title, telling users what the inline frame contains and helping them decide whether to interact with it.

Removing the Border

By default, <iframe> comes with a border. Usually, we want to remove it for seamless embedding. This can be achieved using CSS's border property:

<iframe src="demo_iframe.htm" style="border:none;" title="Iframe Example"></iframe>

Or define it in a stylesheet:

iframe { border: 0; }

The <iframe> target Attribute

An <iframe> can be used as a target for links. If you have a link on a page and want the link's content to display in the <iframe> when clicked, you can do this:

  1. Set a name attribute for the <iframe>.
  2. Set the link <a> tag's target attribute to the <iframe>'s name value.

Example:

<iframe src="default.html" name="myFrame" height="300" width="500"></iframe>

<p><a href="https://www.w3.org" target="myFrame">Open W3.org in Iframe</a></p>

Clicking the link will load the W3C website into the <iframe> named myFrame.