CSS code to make YouTube embed video responsive

By F.A Mollick

Share on

YouTube-Responsive-Embed-CSS

Hello. I am here to help you. You can find that when you get the embed code from YouTube video under share tab than you can find that the video is of fixed width and height. The code you get from YouTube is something like this that given below:

 

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

 

You can notice that the code will make the video with fixed width 420px and height 315px. Now this size of video will not be perfect for all device as the screen width are different. Now lets see what to do.

 

1.First remove the height and width from the above YouTube embed <iframe> code. Now it looks like below

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

2. Now add the div class and put the YouTube embed code inside the div class.

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

 

3. Now the CSS code for the div class “yt-container” and <iframe> inside “yt-container” will be like below:

.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%;
}

 

Now  see the complete code:

HTML code: 

 

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

And the CSS:

 

.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%;
}

 

Thats all. Now try it….

Tags:

Comments are closed.