Адаптивные iframe в Chrome 154

Опубликовано: 16 сентября 2026 г.

Chrome 154 adds support for responsively-sized iframes , letting an <iframe> size itself based on the intrinsic size of its embedded document. This is perfect for seamlessly embedding third-party comment widgets, varying-height social media embeds, or any other type of embed that uses an <iframe> .

Browser Support

  • Chrome: за флагом.
  • Край: за флагом.
  • Firefox: не поддерживается.
  • Safari: не поддерживается.

Source

Responsively-sized iframes replace a common pattern where developers manually measure iframe content, send dimensions with postMessage() and manually update the iframe size in the embedding page.

This recording shows a comment form that is embedded in a page using an iframe. When the user adds their comment, the height of the iframe inside the embedding page dynamically updates, creating a seamless visual experience without any scrollbars.

Изменяйте размер iframe в соответствии с его содержимым.

By default, an iframe has its own viewport. If the embedded document is taller than that viewport, users may get an additional scrollbar. With responsive iframe sizing, the embedding page can instead use content-based sizing:

.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;
}

Изменение размера после динамических изменений контента

Браузер не отслеживает постоянно каждое изменение макета внутри встроенного документа.

If the iframe's content changes after the initial layout, for example after loading more comments or expanding a panel, the embedded document can request a new size calculation with window.requestResize() .

async function loadMore() {
  const items = await fetchMoreItems();
  renderItems(items);
  window.requestResize();
}

It's best to call window.requestResize() before layout, after all changes to the document have been made. This explicit update model helps avoid resize loops where changing the iframe size changes its viewport, which changes its contents, which changes its size again.

Встраивание из разных источников

Адаптивное изменение размера также можно использовать с iframe-элементами, работающими с разными источниками. Встроенный документ может ограничивать список разрешенных источников:

<meta
  name="responsive-embedded-sizing"
  content="allow-origins=https://publisher.example">

Это ограничит адаптивное изменение размеров только до https://publisher.example . Несколько источников разделены пробелом: content="allow-origins=https://publisher1.example https://publisher2.example" .

For third-party widgets, restrict access to the origins that need it. This mechanism complements existing iframe security controls such as Content Security Policy's frame-ancestors directive, which controls which sites can embed a page.

Прогрессивное улучшение

Вы можете использовать запросы функций, чтобы сохранить существующий резервный вариант для браузеров, которые не поддерживают 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 в следующем примере :