fluid width oEmbed videos in WordPress

Here’s the problem: Video elements embedded from YouTube, Vimeo, etc, generally don’t comply with a max-width:100% declaration in your beautiful fluid-width layout. This is because these embeds are generally presented in an iframe which causes some trickery. Ideally, we could present a javascript-free approach…

Note: If you’ve implemented some type of HTML5 video solution, a simple video{ max-width:100%; height:auto; } will be sufficient and will work wonderfully.

Luckily, the Web Designer Wall published a method that we’re going to use. It’s a fancy bunch of CSS. I’d just grab it and throw it in your stylesheet.

The CSS

[css]
.video-container {
position: relative;
padding-bottom: 56.25%;
padding-top: 30px;
height: 0;
/* overflow: hidden; */
}

.video-container iframe,
.video-container object,
.video-container embed {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
[/css]

edit: The overflow:hidden style was causing my site to cease scrolling (everything outside the viewport was… hidden?) It didn’t really make sense, but deleting the line didn’t seem to have an adverse effect… for now..

In fact, that’ll work just fine as long as you wrap some sort of container (such as a <div>) around your oEmbed URL… But that’s too much work, the point of oEmbeds is to be super quick and simple.

Filter the oEmbed

oEmbedding actually runs the URLs it finds through the shortcode and just before it outputs HTML, it applies the embed_oembed_html filter. We can make use of this to very easily wrap a container (as required by the above CSS) and add a layer of semantics by using the HTML5 <figure> tag.

[php]
add_filter( ’embed_oembed_html’, ‘tdd_oembed_filter’, 10, 4 ) ;

function tdd_oembed_filter($html, $url, $attr, $post_ID) {
$return = ‘<figure class="video-container">’.$html.'</figure>’;
return $return;
}
[/php]

5 thoughts on “fluid width oEmbed videos in WordPress

  1. Thank you so much, I have been trying to create make my media queries template to resize youtube videos for mobile phones. This worked perfectly. It took a while to google search for your site, but I found you in the end!

  2. This seems exactly what I’m looking for however I have one question. Where do I put this filtering code? I understand this isn’t a tutorial, but for me you’ve jumped a bit too much and I couldn’t follow.

Leave a Reply

Your email address will not be published. Required fields are marked *