Embed a YouTube Video

Embedding a YouTube video into a site is pretty straight forward. You simply click the ‘Share’ button under a video and click the ‘Embed’ tab and copy the <iframe> code and paste it where you want it displayed on your website.

Embed Code YouTube Screenshot

There’s just one problem with this, if you paste the code as is the videos won’t resize and adjust according to the browser’s width. This is because the size of the video is statically declared, with YouTube the default attributes are ‘width=”560″‘ ‘height=”315″‘. Declaring static widths in fluid width environments can cause problems. What if the parent container for that video shrinks narrower than the declared 560px? It will bust out of the container and look embarrassing.

Create a JS Function that Re-sizes with the Browser

To solve this I like to use JavaScript. Let’s create a JS function with one parameter that measures the width of our iframe to calculate the height. We set our aspect ratio to 16:9. Set the element to 100% width, measure that width. Then times the width times the aspect ratio height then devide that by the aspect ratio width and we get the new height of the element, then we set the height of the element. Lets run this function when the page loads and whenever the browser is resized.

Requires jQuery

// function accepts one parameter
function vidResize(e){
  // aspectRatio = 16:9
  var aspectRatioW = 16;
  var aspectRatioH = 9;
  // set element width to 100%
  jQuery(e).attr('width', '100%');
  // get the elements new width
  var w = $(e).width();
  // calculate the new height
  var h = (w*aspectRatioH)/aspectRatioW;
  // set elements new height
// call vidResize() function on page load & browser resize
jQuery(window).on('load resize', function(){

Now all you need to do is remove the default width & height in your videos iFrame and add a class to your iFrame.

<iframe width="560" height="315" class="resize-this"

Remove the red and add the green.

View this in action here on my codepen.

See the Pen iframe videos rescale with screen by Justin Estrada (@justinestrada) on CodePen.

If you have any questions or remarks, leave a comment down below.