eva 🛹's profile picture

Published by


Category: Web, HTML, Tech

Fluid YouTube embeds

This post assumes you know some HTML/CSS.

If you want to embed a YouTube video, you might notice it doesn't automatically resize. Adding width="100%" to it doesn't work either, you'll get the wrong aspect ratio for your video.

Here's one way to fix that.

First you want to wrap your YouTube embed code in a container like a div. I added the class name "embed" so I can later refer to it in CSS.

<div class="embed"><iframe src="https://www.youtube-nocookie.com/embed/gKNhwHqwV2Y" frameborder="0" allowfullscreen=""></iframe></div>

Now the CSS.

    position: relative;
    padding-bottom: 56.25%;
    height: 0;

.embed iframe
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;

That will always make the container the correct ratio (16:9), and the video inside it will fill up that space. If the video is a different ratio, you'll have to use a different padding-bottom % value. For 4:3 videos you should use 75%. You can calculate this yourself by doing height ÷ width, then multiplying that by 100.

25 Kudos


Displaying 0 of 0 comments ( View all | Add Comment )