Background
Prior to 2021, I was doing it with JavaScript. Using getComputedStyle
combined with window resize
listener to (re)define the height
of an iframe
😐
But now, we have aspect-ratio
.
So..
begone all that hassle
Here's how we do it purely using CSS.
Example Implementation
For example, we want to embed an iframe
from YouTube to our blog and want the thing to be responsive, as in using 100% (or other percentage) of width
of the container and let the height
automatically follows the ratio (done by browser).
Let's use 16:9
ratio for this example.
We get this kind of embed code from YouTube usually:
We can omit the height
, width
, and frameborder
from it, and add class
for the iframe
. Let's use YT_EMBED
as the class of the iframe
.
For clarity, I'll make the attributes to have new lines. So then it will look like this:
And then, we define the CSS rules for that class .YT_EMBED
.
Put all together, it will look like this:
That's about it. It will automatically be in 16:9 ratio.
Neat!
Demonstration
This is an example of an iframe
embedding another iframe
.
Reference
- Aspect ratio documentation at MDN
Comments
Post a Comment