Tech Tip: Embed Videos Responsively

Mia E Lee
Mia Ellis-Lee
Design & Frontend Development
Write to Mia
Share

Disclaimer: Embedding a responsive video requires web development experience and a working knowledge of HTML and CSS.

While embedding YouTube videos into your website can be easily done thanks to YouTube’s automatically generated embed code, often times you’ll find that simply pasting in the code supplied by YouTube will result in a video that doesn’t scale responsively or just doesn’t fit right in the layout of your website.

These next steps will take you through the process of tweaking your HTML structure and CSS in order to make your embedded YouTube videos responsive. This solution will work for any videos that are embedded in an iFrame, such as those from YouTube or Vimeo. This will not address videos that use a standard HTML5 <video> tag since this HTML element can easily be made responsive.

  1. Navigate to the YouTube video you’d like to embed. Under the video, click the “Share” button, and select “Embed”. Copy the HTML code that appears and paste this markup where you’d like it to appear.
  2. Wrap your markup from YouTube in an wrapper <div>. Your code should appear as below:

    <div class="video-wrapper">
    <iframe width="560" height="315" src="https://www.youtube.com/embed/mrZRURcb1cM" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen>
    </iframe>
    </div>

  3. The rationale behind this method is that we will absolutely position the <iframe> within the wrapper <div>. This wrapper <div> (thanks to the CSS code we are about to add) will maintain an consistent aspect ratio regardless of browser size, screen size, or device. Giving the video wrapper the CSS property of “padding-bottom: 56.25%;” will result in a 16:9 video wrapper. Padding set as a percentage uses the width of the containing block to determine the padding applied and changes dynamically - this is what allows our video wrapper to be responsive while maintaining the same aspect ratio. Apply the CSS below to your markup.

    .video-wrapper {
      position: relative;
      padding-bottom: 56.25%;
      height: 0;
    }

    .video-wrapper iframe {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
    }

You can also use simple division to calculate your desired padding percentage. For example, in order to gain a 16:9 aspect ratio, we used a 56.25% padding-bottom value. This is because 9/16 = 0.5625. A video wrapper for a 4:3 aspect ratio would use a 75% padding-bottom value (3/4 = 0.75). You can also manually adjust your padding to get your desired aspect ratio.

Of course, you might need to slightly tweak your CSS in order to get your video embeds to fit perfectly, depending on your layout, but embedding a responsive YouTube video can be as simple as this! You can see a live example here. Embedding a responsive YouTube video can be as easy as 1, 2, 3!

Back to Top Arrow Up