The Problem
I was working on a side-project app and working with markdown notes. All was going well until I tried to embed a YouTube video. Then all the styling went to crap. No matter what I tried, I couldn't get the video to fit the space and maintain aspect ratio.
The Solution
The solution was simple... Google it!
I found this great post on DailyMotion: How to preserve the player aspect ratio on a responsive page
The post said it was a "simple and common CSS trick to preserve the aspect ratio." Well, great! Always a good time to learn the basics.
The Trick
The trick is to wrap the <iframe>
in a <div>
container and then style the <div>
with a specific padding-bottom
relative to the aspect ratio you want to preserve.
Then you make the <iframe>
's width
and height
100% and set the position
to absolute.
The Code
Here is, roughly, what I am using in my YouTube player shortcode:
<div style="position:relative;padding-bottom:56.25%;">
<iframe style="width:100%;height:100%;position:absolute;left:0px;top:0px;"
class="yt-shortcode"
frameborder="0" width="100%" height="100%"
allowfullscreen allow="autoplay"
title="YouTube video player"
src="https://www.youtube-nocookie.com/embed/${id}"></iframe>
</div>
Aspect Ratio Chart
At the end of the post they include a helpful chart of which padding-bottom
values to use to keep specific aspect ratios.
Aspect Ratio | Padding-Bottom |
---|---|
1:1 | 100% |
16:9 | 56.25% |
4:3 | 75% |
3:2 | 66.66% |
8:5 | 62.5% |