Make Embedded iframes Responsive in WordPress

Embedded videos aren’t responsive by default based on the fixed width and height attributes within iframes. When using the Classic Editor, iframes need to be wrapped in a div with a CSS class to style the iframes. The JavaScript and CSS method below will allow you to make all embedded iframes responsive.

Add this to the theme’s functions.php file to auto-wrap iframes.

<?php
function evo_footer_scripts() {
?>
<script>
	(function($) {
		$('iframe').wrap('<div class="iframe-container" />');
	})(jQuery);
</script>
<?php
}
add_action( 'wp_footer', 'evo_footer_scripts' );

The result will be like the example below, automatically wrapping the iframes and adding the iframe-container CSS class to the div.

<div class="iframe-container">
	<iframe title="Video Title" width="1080" height="608" src="https://www.youtube.com/embed/xxxxxxxxxxx?feature=oembed" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen=""></iframe>
</div>

Then add the CSS below to the theme’s existing stylesheet to style all the iframes.

div.iframe-container {
	position: relative;
	padding-top: 56.25%;
	overflow: hidden;
}
div.iframe-container iframe {
	position: absolute;
	top: 0;
	left: 0;
	width: 100%;
	height: 100%;
	border: 0;
}

Note that the CSS value above (padding-top: 56.25%;) sets the responsive aspect ratio to the typical 16:9 aspect ratio (9/16 = 0.5625), and can be modified as needed.

When using the default WordPress Editor, you don’t need to do any of the steps above, you only need to add the new theme support for responsive embeds using the code below in the theme’s functions.php file, within the after_setup_theme hook.

add_theme_support( 'responsive-embeds' );