How to make oEmbed videos responsive

how-to-make-oembed-videos-responsive

If you are using standard HTML5 video, a simple video{ max-width:100%; height:auto; } will be sufficient to make it fit to the width of container. But 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 or object which causes some trickery.

In most scenarios, the video will be wrapped as:

<video width="400" height="300" ... 

or

<iframe width="400" height="300" ... 

or

<object width="400" height="300" ...

So the solution is to wrap the embed code in a container that would allow you to apply some generic CSS that would ensure the video maintains its proportion and fits to the width of container.

The HTML markup would be as follows:

<div class="responsive-video">
    <!-- Copy & Pasted from YouTube -->
    <iframe width="560" height="349" src="http://www.youtube.com/embed/n_dZNLr2cME?rel=0&hd=1" frameborder="0" allowfullscreen></iframe>
</div>

The CSS

First, we style the containing wrapper with the .responsive-video class. Then throw these CSS to your stylesheet.

.responsive-video {
    position: relative;
    padding-bottom: 56.25%; /* 16:9 */
    padding-top: 30px;
    height: 0;
    overflow: hidden; 
}

.responsive-video iframe,
.responsive-video object,
.responsive-video embed {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
}

If you are using wordpress, it’s really a headache if you have to add HTML to every embed video. But there is a filter we can make use of: embed_oembed_html

PHP

Put following snippet to your functions.php

add_filter('embed_oembed_html', 'ct_wrap_embed_container', 10, 3);

function ct_wrap_embed_container($html, $url, $attr) {
        return "<div class=\"responsive-video\">".$html."</div>";
}

Once you have added everything, all your videos that were embedded in a post of your wordpress blog will now be wrapped in this container responsive-video.

Reference:
http://diywpblog.com/embed-responsive-videos-with-wordpress/
http://www.smashingmagazine.com/2014/02/27/making-embedded-content-work-in-responsive-design/

Save

Author: Leo

My name is Leo who's behind this blog. I've been working with wordpress since 2010. I'll write about themes, plugins, tutorials and all about wordpress here. Hope you find it useful!

Leave a Reply

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