如何确保 iFrame 的纵横比是响应式的?

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

我有一个很简单的问题。 如何确保 iframe 的纵横比是响应式的?

iframe 是一个 YouTube 视频,无论浏览器 window 大小如何,我都希望 iframe 的纵横比保持 16:9。

这是我当前的移动设备代码:

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

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

因为 YouTube iframe 不会自动保持纵横比,我需要一种方法来保持视频的纵横比,并且宽度为 90vw。当前代码的问题是,它只调整宽度,留下不需要的信箱。

将 iframe 包装在容器中。

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

您确实不需要媒体查询来实现此目的,但如果您愿意,可以将其转移到媒体查询中。那么,它是如何实现的呢?

因为,我们知道我们需要aspect ratio of 16:9并且宽度不应超过90vw,因此高度也不应超过50.85vw。我们根据您的绝对尺寸限制设置 max-height and max-width,即容器的 600px 和 338 px。 现在,设置 iframe dimensions to the 100% of the container,它会继承该尺寸。 :)

.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>