21 Mar.2017

Youtube: Fluid Width Video

CSS & JS: Make Youtube responsive

You can make YouTube videos responsive with CSS. Wrap the iframe in a div with the class of "youtube-container" and apply the following styles (see below).
The .youtube-field-player div should be inside a responsive element. The padding on the .youtube-container is necessary to keep the video from collapsing. You may have to tweak the numbers depending upon your layout.

File
your.js
  /**
   * Make Youtube responsive.
   *
   * @type {{attach: attach}}
   */
  Drupal.behaviors.responsiveVideos = {
    attach: function (context, settings) {
      var $all_videos = $('iframe[src^="https://www.youtube.com"]', context);
 
      $all_videos.each(function () {
        if (!$(this).hasClass('youtube-field-player')) {
          $(this).addClass('youtube-field-player').wrap('<figure class="youtube-container"></figure>');
        }
      });
    }
  };
File
your.css
.youtube-container {
    margin: 0;
    position: relative;
    padding-bottom: 56.25%;
    height: 0;
    overflow: hidden;
    max-width: 100%;
}
 
.youtube-container .youtube-field-player {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
}

Ruslan Piskarov

Ukraine
PHP/WEB Developer / Drupal Expert. More than 11 years of experience delivering Drupal based General Purpose solutions for different sectors such as Job Boards, Product Portfolios, Geo Coding, Real Estate solutions, E-Commerce, Classifieds, Corporate and online Magazines/Newspapers.

Versions