141

I have a YouTube video embedded on our website and when I shrink the screen to tablet or phone sizes it stops shrinking at around 560px in width. Is this standard for YouTube videos or is there something that I can add to the code to make it go smaller?

MattM
  • 3,089
  • 7
  • 40
  • 62
  • 2
    Good resource to generate your responsive embed code: http://embedresponsively.com/ – ThisClark Jul 23 '17 at 00:45
  • For people visiting this question in 2022 or later, aspect-ratio is probably the answer you're seeking. See https://stackoverflow.com/a/68433058/2496827. 1 line of css, no js. – Matt Pennington Feb 24 '22 at 21:24

11 Answers11

304

You can make YouTube videos responsive with CSS. Wrap the iframe in a div with the class of "videowrapper" and apply the following styles:

.videowrapper {
    float: none;
    clear: both;
    width: 100%;
    position: relative;
    padding-bottom: 56.25%;
    padding-top: 25px;
    height: 0;
}
.videowrapper iframe {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
}

The .videowrapper div should be inside a responsive element. The padding on the .videowrapper is necessary to keep the video from collapsing. You may have to tweak the numbers depending upon your layout.

magi182
  • 3,427
  • 1
  • 15
  • 23
  • 1
    Thank you! I had to add a width:100% to my #content to make sure it was a responsive element. – MattM Apr 06 '13 at 02:47
  • 7
    See also: http://css-tricks.com/NetMag/FluidWidthVideo/Article-FluidWidthVideo.php – Blazemonger Jun 04 '14 at 19:46
  • 1
    in my case the video does not appear when applying this CSS. – basZero Jun 01 '15 at 13:06
  • 6
    the detail explanation on the number `56.25%` and `25px` can be read at http://alistapart.com/article/creating-intrinsic-ratios-for-video `padding-bottom: 56.25%`: To create a 16:9 ratio, we must divide 9 by 16 (0.5625 or 56.25%). `padding-top: 25px`: To avoid issues with the broken box model (IE5 or IE6 in quirks mode), we use padding-top rather than height to create room for the chrome. – Tun Mar 27 '16 at 06:17
  • You can watch the youtube iframe example Here @ [http://alistapart.com/d/creating-intrinsic-ratios-for-video/example4.html](http://alistapart.com/d/creating-intrinsic-ratios-for-video/example4.html) – Vignesh Chinnaiyan Jun 04 '16 at 12:00
  • @magi182 I had the same problem as original poster, your method works for me except I dont want the video to take up the full 100% width, so I changed height in width in vifdeowrapper iframe css to 60% which except it is not horizontally centered - I have tried modifying position attributes and setting left to 10% but that doesnt work either and of course I cant hardcode lef tin pixels. – Paul Taylor Jan 25 '17 at 10:26
  • To avoid the video to take up 100% of the width on big screens, add another div around the .videoclasswrapper with the following css: max-width:640px; To center the video, also add: margin-left:auto; margin-right:auto; – Pim Jan 02 '18 at 15:21
  • classic solution – Harry Moreno Jan 31 '19 at 22:37
  • @Vignesh Chinnaiyan The example link is a 404 Not Found. – StackOverflowUser Feb 28 '21 at 06:57
  • we should remove the iframe width and hight attrs – mercury Jun 04 '21 at 18:09
  • What did I do wrong, I couldn't get it to work? https://jsfiddle.net/xa1jtyr5/ –  Aug 01 '21 at 15:43
30

If you are using Bootstrap you can also use a responsive embed. This will fully automate making the video(s) responsive.

http://getbootstrap.com/components/#responsive-embed

There's some example code below.

<!-- 16:9 aspect ratio -->
<div class="embed-responsive embed-responsive-16by9">
  <iframe class="embed-responsive-item" src="..."></iframe>
</div>

<!-- 4:3 aspect ratio -->
<div class="embed-responsive embed-responsive-4by3">
  <iframe class="embed-responsive-item" src="..."></iframe>
</div>
illage4
  • 455
  • 5
  • 8
10

Refined Javascript only solution for YouTube and Vimeo using jQuery.

// -- After the document is ready
$(function() {
  // Find all YouTube and Vimeo videos
  var $allVideos = $("iframe[src*='www.youtube.com'], iframe[src*='player.vimeo.com']");

  // Figure out and save aspect ratio for each video
  $allVideos.each(function() {
    $(this)
      .data('aspectRatio', this.height / this.width)
      // and remove the hard coded width/height
      .removeAttr('height')
      .removeAttr('width');
  });

  // When the window is resized
  $(window).resize(function() {
    // Resize all videos according to their own aspect ratio
    $allVideos.each(function() {
      var $el = $(this);
      // Get parent width of this video
      var newWidth = $el.parent().width();
      $el
        .width(newWidth)
        .height(newWidth * $el.data('aspectRatio'));
    });

  // Kick off one resize to fix all videos on page load
  }).resize();
});

Simple to use with only embed:

<iframe width="16" height="9" src="https://www.youtube.com/embed/wH7k5CFp4hI" frameborder="0" allowfullscreen></iframe>

Or with responsive style framework like Bootstrap.

<div class="row">
  <div class="col-sm-6">
    Stroke Awareness
  <div class="col-sm-6>
    <iframe width="16" height="9" src="https://www.youtube.com/embed/wH7k5CFp4hI" frameborder="0" allowfullscreen></iframe>
  </div>
</div>
  • Relies on width and height of iframe to preserve aspect ratio
  • Can use aspect ratio for width and height (width="16" height="9")
  • Waits until document is ready before resizing
  • Uses jQuery substring *= selector instead of start of string ^=
  • Gets reference width from video iframe parent instead of predefined element
  • Javascript solution
  • No CSS
  • No wrapper needed

Thanks to @Dampas for starting point. https://stackoverflow.com/a/33354009/1011746

Community
  • 1
  • 1
mindriot
  • 14,149
  • 4
  • 29
  • 40
  • Works perfectly! Thank you so much :) – Laran Evans Mar 05 '16 at 23:23
  • This helps. Especially in cases where you have no control over the HTML elements (but JS) and cannot set a videowrap. Thank you. – Avatar Apr 15 '16 at 12:38
  • Note that this solution will bind the resize event with a JavaScript function, which may put stress on the browser as more events are added. Remember that you can use JavaScript to wrap the iframe in a wrapper div to let the CSS handle the responsive styling and boost performance. –  Jun 21 '16 at 14:54
  • I have tried many solutions. This is the best solution on the Internet to make YouTube Videos responsive. – Dan Nick Feb 09 '17 at 05:41
9

I used the CSS in the accepted answer here for my responsive YouTube videos - worked great right up until YouTube updated their system around the start of August 2015. The videos on YouTube are the same dimensions but for whatever reason the CSS in the accepted answer now letterboxes all our videos. Black bands across top and bottom.

I've tickered around with the sizes and settled on getting rid of the top padding and changing the bottom padding to 56.45%. Seems to look good.

.videowrapper {
    position: relative;
    padding-bottom: 56.45%;
    height: 0;
}
McNab
  • 6,767
  • 4
  • 35
  • 55
  • 1
    Just an update on this - sometimes the old placeholder images used on the videos make it look like there are still black bands top and bottom but the videos themselves look good with this new setting when you actually start playing them. Grrr, thanks YouTube. – McNab Aug 19 '15 at 16:12
  • 1
    Thanks. Using padding-bottom: 50% gets rid of the top and bottom black bars for the video I am using, although it seems that the thumbnail and the video itself have mismatched aspect ratios... – MSC Apr 03 '17 at 03:45
6

Modern simple css solution

The new aspect-ratio is the modern solution to this problem.

aspect-ratio: 16 / 9;

That's all you need to make a div, image, iframe size automatically. Samples.

It's got good support, but is not yet in Safari (will be for upcoming iOS15) - so for now you'll still need to use a fallback. You can achieve that with the @supports feature

.element 
{
   aspect-ratio: 16 / 9;

   @supports not (aspect-ratio: 16 / 9) 
   {
       // take your pick from the other solutions on this page
   }
 }

Assuming your development browser does support this property be sure to test without it by commenting out both aspect-ratio and @supports.

Simon_Weaver
  • 140,023
  • 84
  • 646
  • 689
  • It's been supported in Safari since 15 was released, the @supports is probably not neccessary anymore. – Matt Pennington Feb 24 '22 at 21:14
  • 1
    A LOT of people aren't yet using 15. A quick look on my website (mainly US) shows about 10% of people are on 14 or even 13. Over the past 30 days. – Simon_Weaver Feb 25 '22 at 03:37
5

@magi182's solution is solid, but it lacks the ability to set a maximum width. I think a maximum width of 640px is necessary because otherwhise the youtube thumbnail looks pixelated.

My solution with two wrappers works like a charm for me:

.videoWrapperOuter {
  max-width:640px; 
  margin-left:auto;
  margin-right:auto;
}
.videoWrapperInner {
  float: none;
  clear: both;
  width: 100%;
  position: relative;
  padding-bottom: 50%;
  padding-top: 25px;
  height: 0;
}
.videoWrapperInner iframe {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}
<div class="videoWrapperOuter">
  <div class="videoWrapperInner">
    <iframe src="//www.youtube.com/embed/C6-TWRn0k4I" 
      frameborder="0" allowfullscreen></iframe>
  </div>
</div>

I also set the padding-bottom in the inner wrapper to 50 %, because with @magi182's 56 %, a black bar on top and bottom appeared.

Pascal Klein
  • 23,665
  • 24
  • 82
  • 119
2

This is old thread, but I have find new answer on https://css-tricks.com/NetMag/FluidWidthVideo/Article-FluidWidthVideo.php

The problem with previous solution is that you need to have special div around video code, which is not suitable for most uses. So here is JavaScript solution without special div.

// Find all YouTube videos - RESIZE YOUTUBE VIDEOS!!!
var $allVideos = $("iframe[src^='https://www.youtube.com']"),

// The element that is fluid width
$fluidEl = $("body");

// Figure out and save aspect ratio for each video
$allVideos.each(function() {

    $(this)
    .data('aspectRatio', this.height / this.width)

    // and remove the hard coded width/height
    .removeAttr('height')
    .removeAttr('width');

});

// When the window is resized
$(window).resize(function() {

    var newWidth = $fluidEl.width();

    // Resize all videos according to their own aspect ratio
    $allVideos.each(function() {

        var $el = $(this);
        $el
        .width(newWidth)
        .height(newWidth * $el.data('aspectRatio'));

    });

// Kick off one resize to fix all videos on page load
}).resize();

// END RESIZE VIDEOS
Dampas
  • 323
  • 2
  • 6
2

If you are using Bootstrap 5.0, you can use .ratio

https://getbootstrap.com/docs/5.0/helpers/ratio/

Example

<div class="ratio ratio-16x9">
  <iframe src="https://www.youtube.com/embed/zpOULjyy-n8?rel=0" title="YouTube video" allowfullscreen></iframe>
</div>
Mir Rahed Uddin
  • 1,208
  • 2
  • 12
  • 25
1

With credits to previous answer https://stackoverflow.com/a/36549068/7149454

Boostrap compatible, adust your container width (300px in this example) and you're good to go:

<div class="embed-responsive embed-responsive-16by9" style="height: 100 %; width: 300px; ">
<iframe class="embed-responsive-item" src="https://www.youtube.com/embed/LbLB0K-mXMU?start=1841" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen="" frameborder="0"></iframe>
</div>
Nick Kovalsky
  • 5,378
  • 2
  • 23
  • 50
-2

Okay, looks like big solutions.

Why not to add width: 100%; directly in your iframe. ;)

So your code would looks something like <iframe style="width: 100%;" ...></iframe>

Try this it'll work as it worked in my case.

Enjoy! :)

Umesh Patil
  • 4,668
  • 32
  • 24
  • 6
    Because this doesn't resize the height correctly for the video, and therefore shows controls & black strips, the accepted answer is a better solution – CᴴᵁᴮᴮʸNᴵᴺᴶᴬ Aug 03 '16 at 08:20
  • Since this is the starting point to make responsive videos with embedded iframes, I believe this solution correctly answers the question. Combine this with a grid system and the height is the only issue left. => (container width / 12) * 9 = height. – Tim Vermaelen Jan 27 '17 at 13:20
-2

I make this with simple css as follows

HTML CODE

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

CSS CODE

<style type="text/css">
#vid {

max-width: 100%;
height: auto;

}