Yesterday I was working on a product landing page as I work through the assignments for freeCodeCamp. One part of the assignment was to embed a product video. I embedded a video using the iframe tag supplied by YouTube. I wanted the video to resize responsively as the width of the website was changed.

The first thing I did was set the maximum width of the video to 100vw:

max-width: 100vw;

This made the video resize after the width of browser was less than the width of the video in the iframe tag. But this caused a black bar to appear at the top and bottom of the iframe. I did some searching online to see if I could fine a fix for this. I found some solutions that probably would have worked, but they all looked overly complicated. Here if what I tried instead:

I figured out the height of the video as a percent of the width (height/width). The video was 560px wide and 315px high. 315/560=.5625 or 56.25%. So I set the max-height of the video to 56.25vw.

max-height: 56.25vw;

It worked!

Here is the code:

  <iframe id="video" width="560" height="315" 
src="https://www.youtube.com/embed/D10J6S6KLNQ" frameborder="0"
allowfullscreen></iframe>

  #video {
  display: block;
  margin: auto;
  max-width: 100vw;
  max-height: 56.25vw;
}

Here is my implementation:

Open it up in its own tab (click Edit on CODEPEN), and scroll to the video, then resize your window until the width is less than 560px to see how this works.


456 0 0