[youtube] Shrink a YouTube video to responsive width

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?

This question is related to youtube responsive-design embed

The answer is


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>

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

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;

}


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! :)


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>

See full gist here and live example here.

#hero { width:100%;height:100%;background:url('{$img_ps_dir}cms/how-it-works/hero.jpg') no-repeat top center; }
.videoWrapper { position:relative;padding-bottom:56.25%;padding-top:25px;max-width:100%; }

<div id="hero">
    <div class="container">
        <div class="row-fluid">
            <script src="https://www.youtube.com/iframe_api"></script>
            <center>
            <div class="videoWrapper">
                 <div id="player"></div>
            </div>
            </center>
            <script>
            function onYouTubeIframeAPIReady() { 
                player = new YT.Player('player', {
                   videoId:'xxxxxxxxxxx',playerVars: {  controls:0,autoplay:0,disablekb:1,enablejsapi:1,iv_load_policy:3,modestbranding:1,showinfo:0,rel:0,theme:'light' }
                } );
                resizeHeroVideo();
             }
             </script>
        </div>
    </div>
</div>

var player = null;
$( document ).ready(function() {
    resizeHeroVideo();
} );

$(window).resize(function() {
    resizeHeroVideo();
});

function resizeHeroVideo() {
    var content = $('#hero');
    var contentH = viewportSize.getHeight();
    contentH -= 158;
    content.css('height',contentH);

    if(player != null) {
        var iframe = $('.videoWrapper iframe');
        var iframeH = contentH - 150;
        if (isMobile) {
            iframeH = 163; 
        }
        iframe.css('height',iframeH);
        var iframeW = iframeH/9 * 16;
        iframe.css('width',iframeW);
    }
}

resizeHeroVideo is called only after the Youtube player has fully loaded (on page load does not work), and whenever the browser window is resized. When it runs, it calculates the height and width of the iframe and assigns the appropriate values maintaining the correct aspect ratio. This works whether the window is resized horizontally or vertically.


@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.


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

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


Examples related to youtube

Youtube - downloading a playlist - youtube-dl YouTube Autoplay not working How to embed new Youtube's live video permanent URL? How do you use youtube-dl to download live streams (that are live)? How can I get the actual video URL of a YouTube live stream? YouTube: How to present embed video with sound muted ffprobe or avprobe not found. Please install one Failed to execute 'postMessage' on 'DOMWindow': https://www.youtube.com !== http://localhost:9000 cast_sender.js error: Failed to load resource: net::ERR_FAILED in Chrome Embed YouTube video - Refused to display in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'

Examples related to responsive-design

How to make flutter app responsive according to different screen size? Bootstrap 4: responsive sidebar menu to top navbar How to make canvas responsive Putting -moz-available and -webkit-fill-available in one width (css property) Bootstrap 3 - Responsive mp4-video Change hover color on a button with Bootstrap customization iOS 8 removed "minimal-ui" viewport property, are there other "soft fullscreen" solutions? Bootstrap full responsive navbar with logo or brand name text Bootstrap 3 truncate long text inside rows of a table in a responsive way Responsive Bootstrap Jumbotron Background Image

Examples related to embed

How to embed new Youtube's live video permanent URL? Properly embedding Youtube video into bootstrap 3.0 page How to embed a Google Drive folder in a website How to hide the bar at the top of "youtube" even when mouse hovers over it? How to embed PDF file with responsive width Shrink a YouTube video to responsive width How can I embed a YouTube video on GitHub wiki pages? Embedding a media player in a website using HTML How to embed a YouTube channel into a webpage Embed an External Page Without an Iframe?