HTML 的 iframe 元素

时间:2023-03-09 06:24:48
HTML 的 iframe 元素

在 HTML 中, iframe 元素用于在网页中嵌入其它网页的内容,例如:

<iframe src="http://example.com/abc.html">iframe is not supported</iframe>

其中,iframe 的 src 属性指明要显示的其它网页的地址,而标签中的内容仅在浏览器不支持 iframe 时显示。

对于 iframe 元素,有一些需要注意的问题。首先,从它的名称(inline frame)中可以知道,它是 inline 元素,因此如果要让它填满整个 block 元素,需要设置 iframe 的样式为 display: block。比如下面的例子

<!doctype html>
<head>
<style type="text/css">
div {
width: 480px;
height: 320px;
padding: 0;
overflow: auto;
}
iframe {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
border: 0 none;
}
</style>
</head>
<body>
<div><iframe src="http://www.w3.org"></iframe></div>
</body>
</html>

这个例子中,由于 iframe 默认是 inline 元素,默认它会放在基线之上,而基线之下还有一定高度(即 descender 部分)所以它会溢出了。因此,我们需要设置 iframe 的样式为 display: block 或者 vertical-align: bottom

其次,由于 iframe 是替换元素(replaced element),有一些 CSS 样式对它是无效的。例如,你不能在绝对定位中通过同时设置 top,left,right 和 bottom 四个距离来自动确定它的大小。

在 HTML4 中, iframe 还有不少属性,但在 HTML5 中很多都废弃了,只留下 name,src,width,height 这几个。name 属性指明该页面的名称,width 和 height 指明该 iframe 页面的像素大小(不用加 px)。另外,HTML5 中对 iframe 元素还加入了 srcdoc,seamless 和 sandbox 这三个属性。其中,srcdoc 属性可以指明 HTML 内容,如果 srcdoc 和 src 属性都出现时只使用 srcdoc 属性。而 seamless 属性可以让 iframe 嵌入页面和主页面融为一体,比如将 iframe 元素的样式也应用到 iframe 页面中,又如在主页面中打开 iframe 中的链接。最后的 sandbox 属性将禁止 iframe 页面访问主页面的脚本,cookie 等可能涉及到安全性的内容。

参考资料:
[1] W3C HTML4 - Frames in HTML documents
[2] W3C HTML5 - The iframe element
[3] <iframe> - HTML - MDN[4] HTML: Strange space between iframe elements?