Make YouTube Embed Video Responsive Using CSS

By Faruque Ahamed Mollick

I am here again with another solution which may helpful to you. You will find that when you copy the embed code from YouTube video page under share tab and choose embed, then you will notice that the video is not responsive. It has fixed width and height. So it will not automatically fit the device screen.

Now in this tutorial type post, I am going to give you a solution for this problem. Yes, this is really a problem. If you have a responsive web page then the YouTube embed video will not be responsive and automatically cannot fit with any screen.

For example, suppose you will find the below embed code from YouTube video:

<iframe width="420" height="315" src="https://www.youtube.com/embed/hfQdkBOxXTc" frameborder="0" allowfullscreen></iframe>

Yes, the YouTube video embed code looks same as the above embed code, only the video src or URL may be different. Well if you test it on your web page then you will see that the YouTube player is not responsive. I am now going to solve this problem.



Also, read:

CSS code to make YouTube embed video responsive

Here I am going to give you the CSS code which will make YouTube embed video width 100% and also responsive. This video player will fit with any screen on any device if it is mobile or PC/desktop. Here is the CSS code:

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

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

And the HTML code will be:

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

If you notice to the HTML code then you will find that I remove the height and width from the embed code that I got from YouTube and add the CSS class “yt-container” that I created before.

That’s all you need to do. Now you can test it on your browser and you will see your YouTube embed video on the web page responsive and fit any screen size. PC or mobile, whatever you are using, the YouTube video player will fit with all types of the device screen.

You can use this code inside any div element. The YouTube video on your web page will be automatically adjusted with any div element width.

Leave a Reply

Your email address will not be published. Required fields are marked *