The iframe is still state of the art for embedding content from a number of other webpages, but it is not a naturally responsive object. You can make it responsive, but it takes some effort. I’ve selected some Youtube videos to illustrate.
Doing nothing
Here is a video in standard Youtube syntax:
Since my theme gives iframes a max-width of 100%, it will narrow when you narrow the window, but it won’t change height, adding black bars above and below the content to maintain the aspect ratio of the video itself. This isn’t a big deal when the video is small, but gets more problematic when you want a larger display.
Doing something worse than nothing
Next we can remove the explicitly-set height and width, but that gives you this:
You have to enclose the iframe in a div that adapts its size, but even that takes some effort. Here is the video where the iframe has had its height and width replaced by the tag style="width: 100%;"
, and is enclosed in a div with style="width: 600px; max-width: 100%; position: relative;"
.
You can make it wider or narrower by changing the width style, but it won’t get any taller.
Doing enough
The answer is to play the aspect ratio trick and enclose the iframe in two divs. The outer div controls the width and placement; here it’s set with style="width: 100%; max-width: 700px;"
(700 for dramatic effect). The inner div accommodates the changing height of the box with style="height: 0; padding-bottom: 56.25%; position:relative;"
, where the 56.25% comes from original height 315 divided by original width 560. The iframe has its height and width declarations replaced by style="position: absolute; width: 100%; height: 100%; top: 0; left: 0;"
. Absolute positioning allows it to take up the padding space of its container rather than just the content space (which of course is 0 because of the 0 height). The rest forces it to do so.
All of this styling is inline, so you can see it in the source of this page.
Frames photo by Michael Möller, via Wikimedia Commons.