How to set up responsive on WordPress with YouTube or other embedded videos

WordPress with responsive embedded videos

We are being asked several times about the problem of responsive embedded videos in WordPress.  In this tutorial we’ll try to explain how to solve it easily and quickly.

1st method
By adding a filter and the styles separately.

The goal is to add a parent element that contains the video embedded, in this case we’ll use a <div> tag with the class “wpem-video-container”, for this we must add the following filter in the functions.php file of our (Child-)Theme:

add_filter('embed_oembed_html', 'etruel_oembed_html', 99, 4);
function etruel_oembed_html($html, $url, $attr, $post_id) {
	return '<div class="wpem-video-container">' . $html . '</div >';
}
Add the required styles

We will have to play with the styles of the container element, for this you must add the following CSS rules the style.css of your theme.

	.wpem-video-container {
		position: relative;
		padding-bottom: 56.25%;
		height: 0;
		overflow: hidden;
	}
	.wpem-video-container iframe,
	.wpem-video-container object,
	.wpem-video-container embed {
		position: absolute;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
	}
Another alternative

Another alternative is to add the styles and the filter together in the functions.php file, you can do it this way:

add_filter('embed_oembed_html', 'my_embed_oembed_html', 99, 4);
function my_embed_oembed_html($html, $url, $attr, $post_id) {
	return '
<style>
	.wpem-video-container {
		position: relative;
		padding-bottom: 56.25%;
		height: 0;
		overflow: hidden;
	}
	.wpem-video-container iframe,
	.wpem-video-container object,
	.wpem-video-container embed {
		position: absolute;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
	}
</style>
<div class="wpem-video-container">' . $html . '</div>';
}

However, you must be careful because if a post content several embedded videos, then for each video the same style will be repeated unnecessarily.