WordPress makes it easy to embed third-party content from YouTube, Twitter, Facebook and other websites directly into your post or page by simply pasting the URL of the resource. All sorts of third-party services are supported right out of the box.

The Problem

Unfortunately when embedding a video from YouTube, Vimeo or other video source, WordPress applies a fixed height and width to the embedded element.

This isn’t very desirable: the embedded video is likely to be too small on larger screens like those of laptops and desktops, and too big for handheld devices like phones and tablets, causing dreaded horizontal scrolling.

The Solution

Fortunately there’s an easy way to make our videos responsive automatically. By taking advantage of the embed_oembed_html hook, we can intercept embedded content before it is rendered, adding a wrapper tag that we can then style with CSS.

The Code

First, add the following code to your theme’s functions.php file.

function wptb_wrap_oembed_video( $cached_html, $url, $attr, $post_id ) {
	
	// Look for instances of video providers in oembed content
	$youtube = strpos( $cached_html, 'youtube.com' );
	$vimeo = strpos( $cached_html, 'vimeo.com' );
	
	if( $youtube || $vimeo ){
		// If found, enclose embed content in responsive wrapper
		return '<div class="video">' . $cached_html . '</div>';
	} else {
		// Return embed content unmodified
		return $cached_html;
	}	
}
add_filter( 'embed_oembed_html', 'wptb_wrap_oembed_video', 99, 4 );

Then add the following CSS to your theme:

.video {
    position: relative;
    padding-bottom: 56.25%;
    padding-top: 0px;
    height: 0;
}

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

The Result

Now your embedded videos will automatically grow or shrink to fit their container, like this one:

Photo by Jakob Owens.