responsive YouTube iframe examples of aspect ratios in CSS 16:9

YouTube iframe responsive examples of aspect ratios in CSS 16:9

Posted on

YouTube iframe responsive

YouTube iframe responsive examples of aspect ratios in CSS 16:9
Let’s say you want to embed a YouTube video on your page, and you know that YouTube videos have an aspect ratio of 16:9. But you don’t want to give the iframe a fixed width and height—rather, you want its width to fill its container and for its height to scale responsively, maintaining the element’s 16:9 aspect ratio:



We can do thisusing the padding trick that we learned. To create YouTube iframe responsive an aspect ratio of 16:9, we set the element’s height to be zero and its vertical padding to be 9 / 16 * 100 = 0.5625 * 100 = 56.25%. Again, this just says that the element’s height should be 56.25% of its containing block’s width. The final step is to relatively position the element and absolutely position any children so that they don’t influence the element’s height.

YouTube Embedded Players and Player Parameters

Playing a YouTube Video in HTML and Css

Here’s the HTML that’ll do that for us:

<div class="youtube-embed-container">

Here’s the Css:

.youtube-embed-container {
  position: relative;
  height: 0;
  padding-bottom: 56.25%;
  overflow: hidden;
  /* Not needed if it's a block element, like a div */
  width: 100%;

.youtube-embed-container * {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;

That’s it! Your YouTube iframe will now maintain a responsive 16:9 aspect ratio on all device widths.
Clearly, CSS can be a little weird sometimes—who would’ve thought that padding could be used to create aspect ratios? That thought certainly never crossed my mind until I dug deep into this topic.

With an understanding of padding percentages, you now know how to define responsive aspect ratios in CSS for all kinds of elements, including images, videos, and more. As a bonus, you now also understand how percentage values work for padding and margins and that they depend on the writing mode.

I hope you found this helpful!