How to embed YouTube videos using the correct aspect ratio

By

Learn how to embed a YouTube video with the correct aspect ratio using the CSS aspect-ratio property or Tailwind's aspect-video class, no padding hacks.

~~~

To embed a YouTube video with the correct aspect ratio, set aspect-ratio: 16 / 9 and width: 100% on the iframe. The browser computes the height for you, at any screen size.

I had this problem.

I wanted to embed a YouTube video in a page, but since you need to use an iframe I couldn’t figure out how to properly set the height and width for it, in a way that would work on a fluid layout.

An iframe doesn’t size itself based on its content like an image does. If you only set the width, the height stays at the default and you get black bars above and below the video, or a squashed player.

YouTube videos are 16:9, so we want the height to always be 9/16 of the width. That’s exactly what the CSS aspect-ratio property does.

The solution

Tailwind code with React:

<iframe className="aspect-video w-full"
  src={"Youtube embed URL"}>
</iframe>

Tailwind’s aspect-video class is a shortcut for aspect-ratio: 16 / 9.

Tailwind code without React:

<iframe class="aspect-video w-full"
  src="Youtube embed URL">
</iframe>

Plain HTML and CSS:

<iframe style="aspect-ratio: 16 / 9; width: 100%"
  src="YouTube embed URL"></iframe>

Which URL goes in the iframe?

The YouTube embed URL is something like

https://www.youtube.com/embed/VIDEO_ID

So if you have the video URL you must change that, for example with

videourl.replace('https://www.youtube.com/watch?v=',
  'https://www.youtube.com/embed/')

Be careful with this one. If you put the regular watch?v= URL in the iframe, YouTube refuses to load inside the frame and you get an empty box with a “refused to connect” message. Only the /embed/ URLs work in an iframe.

What about the old padding trick?

Some old tutorials still list the absolute/relative trick, like this:

<style>
.videocontainer {
	position:relative;
	padding-bottom:56.25%;
}
.videocontainer iframe {
	width:100%;
	height:100%;
	position:absolute;
}
</style>

<div class="videocontainer">
  <iframe src="YouTube embed URL"></iframe>
</div>

This works because percentage padding is calculated from the element’s width, and 56.25% is 9 divided by 16. It was the only way to do this before aspect-ratio landed in browsers.

It needs a wrapper element and absolute positioning just to size a box. I prefer the simpler aspect-ratio property, which is one line on the iframe itself.

If you need to work out dimensions for a given ratio, try the aspect ratio calculator.

Tagged: CSS · All topics
~~~

Related posts about css: