Fixing iframe videos on responsive website

Have you ever embedded a video from YouTube or a song from Spotify on a responsive website? Unless there's some sort of css-trick to fix the width and height of the video, it will be oversized and impossible to view on narrow screens.

The simple fix would be to add inside media queries the desired width and height as auto. That works with images. However it doesn't really work with iframes. For them the height gets all wrong.

Fortunately I found a fix. It's an old trick, but seems to still work.

So first you must wrap your iframe thingie with div, that has class video-container. You can name the class anything you want, but let's go with this one for now. It's more clear this way. It would be something like:

<div class="video-container"><iframe allowfullscreen="" frameborder="0" height="315" src="//www.youtube.com/embed/moSFlvxnbgk" width="560"></iframe></div>

Then you need to do a little something to the css-file of your theme or whatnot. Add these two things in there:

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

Basically the padding-bottom on the video-container needs to be something between 50% to 60%. And the iframe (or object or embed) within it needs to have absolute positioning with width and height of 100%. The safest bet is to just copy that stuff above.

This is a reader supported blog without paywalls and advertisement. If you appreciate my work and want to help me rewild the internet, please consider becoming a free or paid patron today. I can't do this without the support of readers like you. So if you can to contribute financially, I would really appreciate your help.

Join free or paid

Mervi Eskelinen

Hello,
I'm Mervi Eskelinen!

An artist, nerd and sorcerer, dedicated to make world softer and better for everyone, and to get you to make more art. Make art, change the world!