Make Embedded YouTube & Vimeo Videos Responsive


Embedding videos in WordPress is really very simple. Just paste the Video URL into the visual editor and boom! Magic happens!

But there is one minor issue. These videos are not responsive by default and will scale incorrectly like this.

YouTube left and Vimeo right with scaling issues.

There are  a number of ways you could fix this, you could go into text editor mode and wrap the video in a div and style accordingly. But we can’t really expect users to do that so another way is to automate that wrapping and styling process.

(function() {
    var fluid_vids = {
        fluid_videos: function () {
            var iframes = document.getElementsByTagName('iframe');
            for (var i = 0; i < iframes.length; i++) {
                var iframe = iframes[i],
                    players = /|;
                if ( > 0) {
                    var videoRatio = (iframe.height / iframe.width) * 100;
           = 'absolute';
           = '0';
           = '0';
                    iframe.width = '100%';
                    iframe.height = '100%';
                    var wrap = document.createElement('div');
                    wrap.className = 'fluid-vids';
           = '100%';
           = 'relative';
           = videoRatio + '%';
                    var iframeParent = iframe.parentNode;
                    iframeParent.insertBefore(wrap, iframe);

Just copy the above code into a file called responsive-video.js file and upload it to your server and then enqueue it as normal. You can enqueue this in the footer and it can also be loaded asynchronously. Winning!

How to enqueue a JavaScript file in WordPress

function responsive_video_js() {
    wp_enqueue_script( 'responsive-videos', '/enter/the/path/to/the.js', '', '1.0.0', true );
add_action( 'wp_enqueue_scripts', 'responsive_video_js' );

Copy the above to your functions.php files and change /enter/the/path/to/the.js to the correct path you uploaded your responsive-video.js file.

Note: The JavaScript above does not require jQuery.

Below you can see both a YouTube and Vimeo video embedded in the standard way and both now scale correctly.




Matthew Horne

Matthew is a web developer from the United Kingdom who taught himself PHP and JavaScript and never looked back. If you would like to hire me, shoot me an email.