Blog

Embedding Responsive YouTube Videos with CSS Only or jQuery
Posted on March 3, 2014 in CSS, jQuery, YouTube by Matt Jennings

I originally found this info in a post from John Surdakowski. Thank you John!

Below are solutions using CSS and another one using jQuery. This should work in WordPress or another CMS.

HTML and CSS

To make a YouTube video responsive wrap the embed code in a div element with 50% to 60% padding-bottom.

Then, inside of the div element style the iframe, object and embed elements so that are absolutely positioned and their width and height are 100%. Below is the HTML and CSS.

HTML with NO jQuery

<div class="youtube-responsive-container">
    <iframe width="560" height="315" src="//www.youtube.com/embed/g9vrNRAqEkU" frameborder="0" allowfullscreen></iframe>
</div>

CSS with NO jQuery

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

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

Responsive YouTube Video Example with NO jQuery

jQuery Example with Updated HTML and CSS

Note: The HTML below does NOT include the div id="content" wrapper element that wraps the YouTube embed iframe. jQuery adds this div id="youtube-responsive-container" wrapper element.

Also a class="youtube-responsive" attribute is added to the iframe to make the YouTube embed responsive. You can see the jQuery JSFiddle here with an example of the responsive YouTube embed. Enjoy!

Updated HTML for jQuery

<div id="content">

    <iframe class="youtube-responsive" width="560" height="315" src="//www.youtube.com/embed/g9vrNRAqEkU" frameborder="0" allowfullscreen></iframe>

</div><!-- #content -->

CSS – Same as Above

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

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

jQuery

// Anonymous function for private variables
(function(){

	// Function to wrap YouTube iframe in <div class='youtube-responsive-container'> tag to make it responsive
	function youtube_embed_responsive() {
		$("#content").find(this).wrap("<div class='youtube-responsive-container'></div>");
	}

	// Assign "this" in funciton below to ".youtube-responsive" YouTube iframe element & iterature over "this" in function using each    
	$(".youtube-responsive").each(youtube_embed_responsive);     

})();

 

Leave a Reply

To Top ↑