Say you wanted to put the CSS-Tricks website in an <iframe> . You’d do that like this:

<iframe src="https://css-tricks.com"></iframe>

Without any other styling, you’d get a rectangle that is 300×150 pixels in size. That’s not even in the User Agent stylesheet, it’s just some magical thing about iframes (and objects). That’s almost certainly not what you want, so you’ll often see width and height attributes right on the iframe itself (YouTube does this).

<iframe width="560" height="315" src="https://css-tricks.com"></iframe>

Those attributes are good to have. It’s a start toward reserving some space for the iframe that is a lot closer to how it’s going to end up. Remember, layout jank is bad. But we’ve got more work to do since those are fixed numbers, rather than a responsive-friendly setup.

The best trick for responsive iframes, for now, is making an aspect ratio box. First you need a parent element with relative positioning. The iframe is the child element inside it, which you apply absolute positioning to in order to fill the area. The tricky part is that the parent element becomes the perfect height by creating a pseudo-element to push it to that height based on the aspect ratio. The whole point of it is that pushing the element to the correct size is a nicer system than forcing a certain height. In the scenario where the content inside is taller than what the aspect ratio accounts for, it can still grow rather than overflow.

I’ll just put a complete demo right here (that works for images too):

See the Pen

Responsive Iframe by Chris Coyier (@chriscoyier)

on CodePen.