YouTube URL

Replace the URL below with whatever YouTube video’s URL you want to make responsive embed code for.

Embed Code

You can select and copy the code below to embed this responsive video in your site.

Example Embed

If you resize the window you will see the video change in size according to the width of the page.

How It Works

The reason this all works is due to the fixed aspect ratio of the YouTube video player and how padding percentages work in CSS.

YouTube Video Aspect Ratio

YouTube always shows videos in a 16:9 aspect ratio.

CSS – Padding Percentages

According to MDN, percentages used for padding “refer to the width of the containing block.”

Combining What We Know

Keeping all of this in mind we first create a container element which will maintain the 16:9 aspect ratio.
{{code.replace(/iframe.+iframe/, '!-- EMBED IFRAME CODE --')}}
  • We use position: relative knowing that the <iframe> is later going to need to have position: absolute.
  • Our padding-bottom: 56.25% comes from our aspect ratio because 9 ÷ 16 = 56.25%.
Now let’s add the embed code (<iframe>):

We use position: absolute; top: 0; left: 0; width: 100%; height: 100%; to make sure that the <iframe> fills the entire container (including the padding).

Concluding Thoughts

You can use this same train of thought to make embeddable videos from any site responsive if you want. The one thing you need to know before hand is the aspect ratio. As long as you know the aspect ratio you will be able to calculate the padding-bottom of the containing element. Happy coding! šŸ˜Ž

Categories: BlogVideos

1 Comment

Alex · December 12, 2019 at 2:45 PM

Thank you!! I was trying to embed dynamic Youtube videos on our site and make it responsive. Due to various reasons, I got on the wrong path on how to solve the problem and started writing a bunch of javascript and doing other silly things to try to dynamically resize the iframe to fit its container. Thank you for your simple and elegant CSS solution!

Leave a Reply

Your email address will not be published. Required fields are marked *