oEmbed youtube video aspect ratio

WordPress does a pretty good job of embedding videos at the correct aspect ratio. The width of the embedded video is based on the content width set in your theme’s functions.php file. Because of this it sounds as if there may be some styles applied to the iframe element in your theme changing it’s size.

To ensure that your videos work at any width within a responsive layout without getting unsightly black borders around the video you’ll need to take a few extra steps.

First you’ll need to wrap the embedded video in a div so that we can apply some styles to it. Add the following to your functions.php file.

function mythemename_wrap_embeds( $html, $url, $attr, $post_id ) {
    return '<div class="video">' . $html . '</div>';
}
add_filter( 'embed_oembed_html', 'mythemename_wrap_embeds', 10, 4 );

Next we’re going to add some styles that setup an intrinsic ratio ensuring the height of the video scales proportionally when the width changes.

.video {
    width: 100%;
    position: relative;
    overflow: hidden;
}

.video:before {
    content: "";
    position: relative;
    padding-bottom: 56.25%;
    height: 0;
    display: block;
    overflow: hidden;
}

.video iframe {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
}

The .video:before element uses padding to set it’s height relative to it’s parent, the .video div. 56.25% is the 16:9 ratio worked out by dividing 9 by 16.

If you need to handle any aspect ratio dynamically, you can skip the above steps and use a jQuery plugin like FitVids.

Leave a Comment