Responsive Video Embeds

Posted December 15, 2013 in Web Development


Update 4/23/14: Just use Fitvids, but this does essentially the same thing.

How to make embedded videos responsive? It is very annoying, especially in WordPress where you can’t count on theme users to modify the HTML. Because embedded media like Youtube and Vimeo videos require a height attribute to be more than 150px tall (that’s the browser default), you would have to adjust the height with media queries which would be unreliable and verbose. Here’s a simple bit of jQuery and CSS that will solve these headaches, wow!

First we wrap all iframe, object, and embed elements in a .media-wrap class that will be styled. This step isn’t necessary if you can just wrap the elements yourself.

// Wrap all media in a figure element 
var $media = $('iframe, object, embed');
$media.wrap( '<figure class="media-wrap"></figure>' );

Then add some styles for the wrapper, courtesy of this blog post by Michael Lancaster.

// Fluid videos
// http://www.bymichaellancaster.com/blog/fluid-iframe-and-images-without-javascript-plugins/
.media-wrap {
    position: relative;
    padding-bottom: 56.25%; /* proportion value to aspect ratio 16:9 (9 / 16 = 0.5625 or 56.25%) */
    padding-top: 30px;
    height: 0;
    overflow: hidden;
    margin-bottom: 2.2em;
}
 
// Note this is SCSS
.media-wrap {
    iframe, object, embed {
        position: absolute;
        top: 0; 
        left: 0;
        width: 100%;
        height: 100%;
    }
}

All of this included in the WPFolio revamp – pretty excited about it.