Embed YouTube video with iFrame without fixed size height and width
In this post, I describe how you can embed a YouTube video in HTML without using a fixed size height and width.
Problem
The problem with a fixed height and width is that the embedded YouTube video doesn't fit once the screen gets narrower than the fixed width (for example, on a mobile device) and you end up with the sides of the video being cut off and horizontal scrollbars:
Resolution
Thanks to CSS tricks for this post which has an excellent solution:
1. Create a container (e.g. a div) and put the embed video code from YouTube inside this container:
<iframe src="https://www.youtube.com/embed/HF7GTGaJdVg"></iframe>
</div>
2. Specify the CSS for the container and the iFrame inside it:
.video-container
{
position: relative;
padding-bottom: 56.63%;
height: 0;
}
.video-container iframe
{
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
The padding-bottom controls the aspect ratio. I tweaked it slightly to 56.63% to ensure no vertical or horizontal black bars appeared on my embedded videos.
The embedded YouTube video now fits correctly at all screen sizes:
The CSS tricks post also contains a clever adaption to allow the aspect ratio to be changed directly in the HTML. Check out the link above to see how.
Comments
Post a Comment