发布时间:2026 年 9 月 16 日
Chrome 154 新增了对自适应尺寸 iframe 的支持,让 <iframe> 可以根据其嵌入文档的固有尺寸自行调整大小。这非常适合无缝嵌入第三方评论 widget、高度各异的社交媒体嵌入内容或使用 <iframe> 的任何其他类型的嵌入内容。
自适应大小的 iframe 可取代一种常见模式,即开发者手动测量 iframe 内容,通过 postMessage() 发送尺寸,并在嵌入页面中手动更新 iframe 大小。
调整 iframe 的大小以适应其内容
默认情况下,iframe 具有自己的视口。如果嵌入式文档的高度高于该视口,用户可能会看到额外的滚动条。借助自适应 iframe 大小调整功能,嵌入网页可以改为使用基于内容的尺寸调整:
.embed {
width: 100%;
frame-sizing: content-height;
}
嵌入式文档必须选择启用:
<meta name="responsive-embedded-sizing" content="allow-origins=*">
以下是完整示例:
<style>
.embed {
width: 100%;
frame-sizing: content-height;
}
</style>
<iframe class="embed" src="/comments.html" title="Comments">
</iframe>
在 /comments.html 中:
<!doctype html>
<html>
<head>
<meta name="responsive-embedded-sizing" content="allow-origins=*">
</head>
<body>
...
</body>
</html>
现在,iframe 可以使用嵌入式文档的内容高度,而不是像固定高度的视口那样运行。
使用 frame-sizing
新的 frame-sizing 属性用于控制从 iframe 的内容派生出哪个维度。
支持的值包括:
frame-sizing: auto;
frame-sizing: content-width;
frame-sizing: content-height;
frame-sizing: content-inline-size;
frame-sizing: content-block-size;
auto 保留现有的 iframe 大小调整行为。
对于大多数横向书写模式,content-height 和 content-block-size 是垂直展开的嵌入内容最有用的值。
您还可以将 frame-sizing 与其他 CSS 限制条件结合使用:
.embed {
width: 100%;
max-height: 80vh;
frame-sizing: content-height;
}
在动态内容更改后调整大小
浏览器不会持续观察嵌入式文档中的每个布局变化。
如果 iframe 的内容在初始布局后发生变化(例如,在加载更多评论或展开面板后),嵌入式文档可以使用 window.requestResize() 请求重新计算大小。
async function loadMore() {
const items = await fetchMoreItems();
renderItems(items);
window.requestResize();
}
最好在布局之前(即在对文档进行所有更改之后)调用 window.requestResize()。这种显式更新模型有助于避免出现调整大小循环,即更改 iframe 大小会更改其视口,进而更改其内容,从而再次更改其大小。
跨源嵌入
自适应尺寸调整功能也可用于跨源 iframe。嵌入式文档可以限制允许哪些来源:
<meta
name="responsive-embedded-sizing"
content="allow-origins=https://publisher.example">
这样会将自适应尺寸调整限制为仅 https://publisher.example。多个来源之间以空格分隔:content="allow-origins=https://publisher1.example https://publisher2.example"。
对于第三方 widget,请将访问权限限制为仅授予需要该权限的来源。此机制可与现有的 iframe 安全控制措施(例如内容安全政策的 frame-ancestors 指令)相辅相成,后者用于控制哪些网站可以嵌入网页。
采用渐进增强的方式
您可以使用功能查询来为不支持 frame-sizing 的浏览器保留现有的后备:
.widget {
width: 100%;
height: 500px;
}
@supports (frame-sizing: content-height) {
.widget {
height: auto;
frame-sizing: content-height;
}
}
如果嵌入的文档会动态更新,您还可以进行功能检测 requestResize():
if ("requestResize" in window) {
window.requestResize();
}
因此,在扩大支持范围的同时,现有的 iframe 大小调整代码可以作为后备方案保留。
试试看
不妨在以下演示中试用自适应 iframe 大小调整功能: