Add a CSS wrapper to make YouTube videos responsive in WordPress

UPDATE: includes solution for new Youtube or Vimeo embed tags.

CSS required for HTML5 video:

video {
  width: 100%    !important;
  height: auto   !important;
}

jQuery required for embedded videos:

TIP: If you use other embed sources, make sure to add to the $allVideos Variable.

$(function() {
    
    var $allVideos = $("iframe[src^='//player.vimeo.com'], iframe[src^='//www.youtube.com'], iframe[src^='http://player.cnevids.com'], object, embed"),
    
   $fluidEl = $("figure"); // change this to your responsive html container
	    	
	$allVideos.each(function() {
	
	  $(this)
	    // jQuery .data does not work on object/embed elements
	    .attr('data-aspectRatio', this.height / this.width)
	    .removeAttr('height')
	    .removeAttr('width');
	
	});
	
	$(window).resize(function() {
	
	  var newWidth = $fluidEl.width();
	  $allVideos.each(function() {
	  
	    var $el = $(this);
	    $el
	        .width(newWidth)
	        .height(newWidth * $el.attr('data-aspectRatio'));
	  
	  });
	
	}).resize();

});

OLD VERSION:

Add this CSS to your page:

.videoWrapper { position: relative; padding-bottom: 56.25%; padding-top: 25px; height: 0; }
.videoWrapper iframe { position: absolute; top: 0; left: 0; width: 100%; height: 100%; }

Add this to your theme’s function.php file:

function add_video_wmode_transparent_and_wrapper($html, $url, $attr) {

	if ( strpos( $html, "<embed src=" ) !== false )
	{ 
		$html = str_replace('</param><embed', '</param><param name="wmode" value="opaque"></param><embed wmode="opaque" ', $html); 
	}
	elseif ( strpos ( $html, 'feature=oembed' ) !== false )
	{ 
		$html = str_replace( 'feature=oembed', 'feature=oembed&wmode=opaque&rel=0&showinfo=0&controls=0', $html ); 
	}
	$return = '<div class="videoWrapper">'.$html.'</div>';
	return $return;
}
add_filter( 'embed_oembed_html', 'add_video_wmode_transparent_and_wrapper', 10, 3);

Reference: http://css-tricks.com/NetMag/FluidWidthVideo/demo.php

2 Replies to “Add a CSS wrapper to make YouTube videos responsive in WordPress”

  1. Thanks so much for this code! Exactly what I was looking for. Now I was able to create a wrapper around all my embedded videos! 🙂

Comments are closed.