Say you wanted to put the CSS-Tricks website in an
. You’d do that like this:
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).
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):
Every time we’re dealing with aspect ratios, it makes me think of a future with better handling for it. There is the experimental
intrinsicsize attribute that I could imagine being quite nice for iframes in addition to images. Plus there is the hopefully-will-exist-soon
aspect-ratio in CSS and the idea that it could default to use the
height attributes on the element, which I hope would extend to iframes.
CSS Tricks Go to Source
Powered by WPeMatico