How Do I Make Sure An iFrame's Aspect Ratio Is

2019-08-19 03:39发布

问题:

I have a very simple question. How do I make sure an iframe's aspect ratio is responsive?

The iframe is a YouTube Video, and I want the aspect ratio of the iframe to remain 16:9 no matter the browser window size.

Here is my current code for mobile devices:

@media screen and (max-width: 600px) {
  iframe, body {
    max-width: 90vw;
    height: auto;
  }
}

iframe {
  border: 0;
  width: 600px;
  height: 338px;
}

Because YouTube iframes do not keep aspect ratio automatically, I need a way to keep the aspect ratio of the video, and the width to be 90vw. The problem with this current code is that, it only adapts the width, leaving unwanted letterboxing.

回答1:

You really don't need media query to achieve this but if you want, you can shift it inside media query. So, how is it being achieved?

Since, we know we need the aspect ratio of 16:9 and the width should not exceed 90vw, thus the height should also not exceed 50.85vw. And we set the max-height and max-width according to your absolute dimension limits that is 600px and 338 px of the container. Now, setting the iframe dimensions to the 100% of the container, it inherits that dimensions. :)

.tv-wrapper {
  max-width:600px;
  max-height:338px;
  width:90vw;
  height:50.85vw;
  margin:0 auto;
}
iframe {
  width:100%;
  height:100%;
}
<div class="container">
      <div class="tv-wrapper">
          <iframe class="sproutvideo-player" src="//videos.sproutvideo.com/embed/489adcb51e1debcdc0/e0d9daac7a1a9b30?
bigPlayButton=false&amp;showControls=false" frameborder="0" allowfullscreen="allowfullscreen"></iframe>
          </div>
    </div>



回答2:

Wrap the iframe in a container.

.media-container {
    position: relative;
    padding-bottom: 56.25%; // = 16:9
}

.media-container iframe {
    position: absolute;
    top: 0;
    left:0;
    right: 0;
    bottom: 0;
    width: 100%;
    height: 100%;
}