Make WordPress default video embeds responsive

Unfortunately WordPress does not add a div around embed codes by default, so this is the first thing we need to do to get it to work.

Add this to your theme’s functions.php:

/*  Add responsive container to embeds
/* ------------------------------------ */	
function alx_embed_html( $html ) {
	return '<div class="video-container">' . $html . '</div>';
}

add_filter( 'embed_oembed_html', 'alx_embed_html', 10, 3 );
add_filter( 'video_embed_html', 'alx_embed_html' ); // Jetpack

And next up, we need to add the CSS that makes it responsive to our style.css:

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

And that’s it! You now make iframe, object, embed and video (html5) elements responsive. The responsive CSS will always show videos in 16:9 aspect ratio, which is HD.

This code will also work with Jetpack embeds.

43 Responses

  1. The Overseer says:

    Thanks man 🙂

  2. moep0r says:

    Thank you so much, I’ve been looking for something like that for soooo long now!

  3. Benson Trent says:

    Thanks! Works Great!

    Benson

  4. David says:

    Hello, I’m trying to use this but it doesn’t automatically add the div around the iframe code. Also tried with your theme and same result.

    Do I need to add the iframe to the post in a special way? I’m doing it right now changing the post editor to text mode and pasting the youtube iframe code.

  5. excellent work alx thanks for sharing this this. really i was wondering after got this function

  6. Hendre says:

    Thanks!! This is perfect..

  7. Daniel says:

    Fantastic spnippet. Works like a charm!!!

    Thanks very much.

  8. Thank you! Finally a full WP solution. 🙂

  9. Paskan says:

    You saved me a lot of time, I can’t thank you enough! This worked perfect for me.

  10. Sanj says:

    Brilliant! Thanks a million!

  11. wamic says:

    Iam sort of new to wordpress….I hope someone will help me like kid
    1.What kind of player i have to use, do I need the video option in the post?
    2. I want to use the player shown in anew theme,

  12. FreakyPanda says:

    Nice and clean, Thanks for sharing

  13. Iyan Riana says:

    OMG! Thank you so much! 🙂

  14. Pradeep says:

    I tried this and it worked like a charm for Youtube. Is there something similar for Vine, please?

  15. Franklin says:

    Very nice and easy, is the best solution in the internet. Greetings from Venezuela

  16. Very helpful, thank you so much!

  17. E-VANCE says:

    Thanks mate, appreciate it!

Leave a Reply

Your email address will not be published. Required fields are marked *