Responsive YouTube Embed

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! šŸ˜Ž