How to embed YouTube/Vimeo videos responsively

You've finally launched your awesome redesign. It's all shiny with HTML5, CSS3, and a responsive layout that looks perfect on your phone—until you embed a YouTube video.

Urgh, that video isn't responsive. Do you spend your time hacking the embed code or just let it ruin your layout?

Next time that happens, try out Embed Responsively. Just paste in the URL for YouTube, Vimeo, Vine, or any of the other services they support. You'll get back a snippet that embeds the video responsively.

Take this adorable video of sloths, for example. Here's the Vimeo embed code:

<iframe src="//;portrait=0" width="500" height="400" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>

And here's the Embed Responsively version:

<style>.embed-container { position: relative; padding-bottom: 56.25%; height: 0; overflow: hidden; max-width: 100%; height: auto; } .embed-container iframe, .embed-container object, .embed-container embed { position: absolute; top: 0; left: 0; width: 100%; height: 100%; }</style><div class='embed-container'><iframe src='' frameborder='0' webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe></div>

It's a bit longer, and I'll admit I'm not a fan of adding a <style> in the HTML, but it works great and you could always move that into your stylesheet instead.

What's your strategy for handling responsive videos?

Author avatar

About the author

Creator of Surreal CMS and other web things. Follow me for tweets about JavaScript, CSS, and web programming.