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

送分小仙女□ 提交于 2019-12-24 21:10:45

问题


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%;
}


来源:https://stackoverflow.com/questions/47841764/how-do-i-make-sure-an-iframes-aspect-ratio-is-responsive

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!