Published on
Last Updated on
Estimated Reading Time: 2 min
I struggled for a long time to get my YouTube videos 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.
Steps
Let's 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
<iframe
width="560"
height="315"
src="https://www.youtube.com/embed/RcnksOUugcA"
frameborder="0"
allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture"
allowfullscreen
></iframe>
Step 1
Remove all unnecessary properties, including width and height. Our snippet now becomes
<iframe src="https://www.youtube.com/embed/RcnksOUugcA" allowfullscreen></iframe>
Step 2
- Add a container with a CSS class around the iframe.
- Add a CSS class to the iframe.
<div class="video-container">
<iframe class="video" src="https://www.youtube.com/embed/RcnksOUugcA" allowfullscreen></iframe>
</div>
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 that is 56.25% of the width.
Note: To find the container aspect ratio, 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.