Making Video Embeds Fluid Width

Updated 19 days ago ​by Jake Peters

If you're embedding videos from Youtube or Vimeo, you might find that they don't occupy the full width of the article. Or that they're even wider, and cause the window to scroll. You can make these embeds fluid with a little custom Javascript. 

If you make your video containers fluid, you'll no longer be able to modify the width on a per-video basis

The Javascript

Paste this snippet into SettingsCode > Custom Scripts
<script>
    $(function () {
        // Add responsive class for Vimeo
        $("iframe[src*='//player.vimeo.com']").closest('.video-container').addClass('vimeo-container');
        // Find all YouTube videos
        var $allVideos = $("iframe[src*='//www.youtube.com']"),
        
            // The element that is fluid width
            $fluidEl = $("#article .card-block"); // NOTE: this may differ on your template
        // Figure out and save aspect ratio for each video
        $allVideos.each(function() {
        
            $(this)
                .data('aspectRatio', (this.height / this.width) || 0.5625)
        
                // 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(); 
    });
</script>

Now your videos should all resize with the window, and default to a nice full-width version 📺


How did we do?