
If you develop responsive WordPress themes, you’re likely making sure embeds and iframes resize within the container. Something like this does the trick:
/* Make sure embeds and iframes fit their containers */
embed,
iframe,
object {
max-width: 100%;
}
But the problem with video embeds is that the aspect ratio isn’t maintained at smaller screensizes. A quick for this is the tiny jQuery plugin FitVids.
There are a few WordPress plugins that enable users to load FitVids on their own- but it requires people to know the CSS selector that wraps the video, and even more importantly, that they need to install the plugin.
I’ve noticed a number of theme companies (Array, Theme Foundry) bundle FitVids.js by default so users don’t need to worry about it at all. I’ve started to do this with my themes as well.
Load FitVids.js from the Theme
To get it set up, download jquery.fitvids.js from the GitHub repo.
Load it from your functions.php file:
wp_enqueue_script( 'prefix-fitvids', get_template_directory_uri() . '/js/jquery.fitvids.js', array( 'jquery' ), '1.0.0', true );
You’ll also need to init the script, so either drop this at the bottom of your jquery.fitvids.js script or another one that you’re loading:
// Init fitVids
jQuery( document ).ready( function ($) {
if ( $.fn.fitVids) {
$('.hentry').fitVids();
}
});
If your content is wrapped in something other than the selector ‘.hentry’ you’ll also want to update that.
Efficient?
FitVids minifies down to 1.7kb- so there’s not that much overhead, especially if you’re loading a script file anyways. Just concat all your script files and load them as one. If you’re interested in reading more about that, see my post on Grunt.
But, if you’re a super performance nerd, read this more recent post about conditionally enqueuing FitVids.