Making Your Website's Youtube Videos Responsive

In class, I’ve demonstrated how to embed YouTube videos in a website. It’s really quite easy. As you will remember, you simply go to the YouTube video, click on share, and copy the embed code. This embed code is what you will insert into your website where you want your video to live.

I’ve emphasized in class how important it is to design a responsive website—a website that rearranges itself depending on the size of your screen or your browser window. The point of having a responsive website is to ensure that your site is easy to use regardless of whether visitors are accessing it on their phones, tablets, laptop, or desktop screens.

If you’ve embedded a YouTube video in your site, you will notice that your YouTube video is not automatically responsive. To make it responsive, you need to modify your CSS.

There are a number of online examples of how to set up your CSS code. I’m recommending a method designed by Thierry Koblentz on the A List Apart blog. This is the method that I’ve been using on my own sites for the past few years. It was updated by Chris Coyler on the CSS-Tricks website just a few days ago (and, if you’re really interested, I recommend checking out his post.

The first thing you need to do is add a little bit of CSS code to your site (if you are using a CMS such as Wordpress or Squarespace, you can easily drop it in using Theme Customizer or Custom CSS respectively).

Here’s the code:

.youtube-video-container {
    position: relative;
    padding-bottom: 56.25%;
    padding-top: 30px;
    height: 0;
    overflow:hidden;
}

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

Here’s what happens…

  • .youtube-video-container creates a CSS class

  • the other settings create a 16:9 aspect ratio that is relative to the container that holds the YouTube video

  • .youtube-video-container iframe, .youtube-video-container embed, .youtube-video-container object define three different types of containers: iframe, embed, and object—all of which are types of wrapper selectors used to embed videos (though, YouTube code uses iframe).

The next thing we want to do is embed our YouTube video in our page, making sure to provide the necessary code for it to be responsive.

Here’s the code:

<div class="youtube-video-container">
  <!-- The section below is the section that you copy and paste from YouTube -->

<iframe width="560" height="315" src="https://www.youtube.com/embed/5dRG80KTIzI" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
  
</div>

This should be all you need to create a responsive page for most YouTube videos.