Embedding Youtube Videos
When copying the embed code from YouTube, a fixed width and height is given for the iframe
. This will probably look ugly on web pages with responsive designs. As iframe
s are not images, there's no way for the browser to know what height to set the frame to. Fortunately, all YouTube embeds are of 16:9 ratio, and we can work around this with a little bit of CSS.
HTML snippet
<div>
<div style="position:relative;padding-top:56.25%">
<iframe src="<youtube-embed-url-here>" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen style="position:absolute;top:0;left:0;width:100%;height:100%;"></iframe>
</div>
</div>
How this works
Notice that we are not using the width
and height
properties, instead we are using CSS style. Two important things makes it work, the first padding-top:56.25
creates a 16:9 aspect ratio div
box for the iframe
to fill up. Next, we set the iframe
's style
to position:absolute;top:0;left:0;width:100%;height:100%;
. This positions the iframe
at the top-left corner of the div
block and sets it occupy the entire block which is of the correct aspect ratio. Now we have an auto-resizing embedded block that's filled with the desired YouTube video!