Make YouTube Video Embeds Responsive Using Pure HTML and CSS

Zach Zach (248)
2 minutes

Surprisingly, normal YouTube embeds are not automatically sized to the browser window as it is resized. Luckily, you can make YouTube videos responsive and mobile-friendly with some simple HTML and CSS.

Posted in these interests:
h/webdev60 guides
h/webdesign17 guides
YouTube logo
h/youtube5 guides

Wrap your embed code in a unique video wrapper (the class name is arbitrary). I chose to use embed-youtube as the selector.

<div class="embed-youtube">
    <iframe src="//www.youtube.com/embed/aCOsM-4NEKs" width="750" height="563"></iframe>
</div>

We'll use a CSS "padding trick" to maintain the video's aspect ratio as the browser is resized. Add the following to your stylesheet:

.embed-youtube {
    position: relative;
    padding-bottom: 56.25%; /* - 16:9 aspect ratio (most common) */
    /* padding-bottom: 62.5%; - 16:10 aspect ratio */
    /* padding-bottom: 75%; - 4:3 aspect ratio */
    padding-top: 30px;
    height: 0;
    overflow: hidden;
}

.embed-youtube iframe,
.embed-youtube object,
.embed-youtube embed {
    border: 0;
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
}

Most YouTube videos use an aspect ratio of 16:9; therefore, I recommend using a value of 56.25% for the padding-bottom property, as noted above. To calculate other aspect ratios, simply divide H/W. For example, let's say you have a video with an aspect ratio of 4:3. Dividing 3÷4 equals 0.75, or 75%. Therefore, padding-bottom would be 75% to maintain this aspect ratio.

Resize your browser window and bask in the responsive glory.

Watch the video:

And then consider embedding one of the most viewed YouTube videos into your next project.

Welcome to the billion views club.
Michael Michael (175)
0

Did you know that the number of views on the most-viewed YouTube video is higher than the number of people on the entire globe?! Yup. We're talking in the billions...and then some.