DEV Community

Ankur Sheel
Ankur Sheel

Posted on • Originally published at on

Full-width YouTube video embed

I struggled for a long time to get my YouTube videos to be full-width with a 16:9 aspect ratio. Then I found a neat CSS trick to make iframes responsive.

But before, we look at the code, let’s look at the before and after screenshots




Let’s see how we can use CSS to display an iframe with 100% width and 16:9 aspect ratio.

When embedding a video from YouTube, we get a snippet of code similar to

    allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture"

Step 1

Remove all unnecessary properties including _ width _ and _ height _. Our snippet now becomes

<iframe src="" allowfullscreen></iframe>

Step 2

  1. Add a container with a CSS class around the iframe.
  2. Add a CSS class to the iframe.
<div class="video-container">
    <iframe class="video" src="" allowfullscreen></iframe>

Step 3

Add CSS to the container

.video-container {
    position: relative;
    width: 100%;
    padding-bottom: 56.25%;

What are we doing here?

  • position: relative: Lets us use absolute positioning for the iframe.
  • width: 100%: Make the width 100% of its parent container.
  • padding-bottom: 56.25%: The 16:9 aspect ratio corresponds to a height which is 56.25% of the width.

Note: To find the aspect ratio of a container, use this formula: height ÷ width = aspect ratio.

Step 4

Add CSS to the iframe

.video {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    border: 0;

What are we doing here?

  • position: absolute: Free the video from the height boundary of its parent and allow it to be positioned over the padding area.
  • top: 0: Position the video at the top of its parent container.
  • left: 0: Position the video at the left of its parent container.
  • width: 100%: Stretch the video to fill the width of its parent container.
  • height: 100%: Stretch the video to fill the height of its parent container.
  • border: 0: Remove the border.

Source Code / React Component

You can play around with it here.

If you want to see an example of the code, I have made a reusable react component that I am using on this website.

Top comments (0)