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.




In Category: WordPress

Matthew Horne

I am a web developer from the United kingdom who taught himself PHP and JavaScript and continues to build on those skills as well as learn new skills.

Show 4 Comments
  • Pedro Lima 7th July 2015, 10:22 pm

    Nice script Matt! No dependencies is a really nice call

  • ted 3rd February 2016, 3:32 am

    when you say “drop i in a file” where/what do you mean?


    • Matthew Horne 9th March 2016, 10:10 am

      Hi I updated the post to add more instructions.

      You need to copy the code to a js file and then enqueue if you are using WordPress.

  • Robert K 26th October 2016, 9:10 pm

    An absolute lifesaver and really nice and clean, thanks so much for sharing!

Leave a Comment