How to make an iframe responsive
Short answer
Stretch the iframe to the full width and set the proportions with aspect-ratio — the height adjusts itself:
<iframe src="https://example.com" title="Example Domain" style="width: 100%; height: auto; aspect-ratio: 16 / 9; border: 0; background: whitesmoke;"></iframe>A video usually needs 16 / 9, a map — 4 / 3 or a square.
Limiting the width
On a large screen a video spanning the whole page looks huge. Add max-width:
<iframe src="https://example.com" title="Example Domain" style="display: block; width: 100%; max-width: 400px; height: auto; aspect-ratio: 16 / 9; margin: 0 auto; border: 1px solid silver;"></iframe>The old way
Before aspect-ratio, the proportions were kept with a wrapper with padding-top: 56.25% (that is 9 / 16) and an absolutely positioned iframe inside. Such code is still common, but in new projects one line with aspect-ratio is enough.
Common mistake
The service gave embed code with width="560" height="315" attributes, and CSS sets only width: 100%. The width changes, but the height from the attribute stays — on a phone the player becomes a narrow tall strip. Add height: auto and aspect-ratio.
Functions used in this recipe
- <iframe> — Embeds another page inside the current one: a map, a video, a widget.
- aspect-ratio — The ratio of width to height: the browser computes the missing dimension.
- width — The width of an element.
- padding — The inner spacing between the content and the border of an element.