You should make all the YouTube videos responsive

Tagged InAllDrupalWebUX

With responsive web design, everything must be fluid, this becomes an issue when you start embedding YouTube videos as they have a fixed height and width.  This results in the video being too small on large screens or too large on small screens. It was becoming an issue with almost every site build. 

So I devised a solution. I might make it into a module one day, but for now it is a snippet.

The JS

(function ($) {

  /**
   * Wrap YouTube iframes in a div so we can make them responsive.
   */
  Drupal.behaviors.responsiveVideoWrapper = {
    attach: function (context, settings) {
      $('iframe[src*="youtube.com"]', context)
        .wrap('<div class="responsive-video-wrapper"></div>')
        .wrap('<div class="responsive-video"></div>')
    }
  };

})(jQuery);

The CSS

.responsive-video {
  position: relative;
  padding-bottom: 56.25%; /* 16:9 */
  padding-top: 25px;
  height: 0;
  iframe {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    border: none;
  }
}

.responsive-video-wrapper {
  max-width: 1200px;
  margin: 0 auto;
}

The SASS

// Mixins 
@mixin responsive-video() {
  position: relative;
  padding-bottom: 56.25%; /* 16:9 */
  padding-top: 25px;
  height: 0;
  iframe {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    border: none;
  }
}
%responsive-video {
  @include responsive-video;
}

// Components
.responsive-video {
  @extend %responsive-video;
}
.responsive-video-wrapper {
  max-width: 1200px;
  margin: 0 auto;
}

This assumes a 16:9 aspect ratio for the videos and apply a max width of 1200px. Once those snippets are added, all youtube videos should be nice and responsive.

 

Testing... Resize your browser

Touch Sensitive - Pizza Guy

Next Article