【问题标题】:How Do I Make Sure An iFrame's Aspect Ratio Is Responsive?如何确保 iFrame 的纵横比是响应式的?
【发布时间】:2018-05-30 05:16:44
【问题描述】:

我有一个非常简单的问题。 如何确保 iframe 的宽高比是响应式的?

iframe 是 YouTube 视频,无论浏览器窗口大小如何,我都希望 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。当前代码的问题在于,它只适应宽度,留下不需要的信箱。

【问题讨论】:

    标签: css iframe youtube responsive aspect-ratio


    【解决方案1】:

    你真的不需要媒体查询来实现这一点,但如果你愿意,你可以在媒体查询中移动它。那么,它是如何实现的呢?

    因为,我们知道我们需要aspect ratio of 16:9,并且宽度不应超过90vw,因此高度也不应超过50.85vw。我们根据您的绝对尺寸限制设置max-height and max-width,即容器的 600 像素和 338 像素。 现在,设置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>

    【讨论】:

      【解决方案2】:

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

      【讨论】:

      • 等一下,我在 w3schools.com 上看到了 padding aspect-ratio 的方法,还有其他方法可以保持宽高比吗?
      • 否 - 填充方法是获取纵横比的方法。 bootstraps embed class 也在使用它。
      • 我使用了填充方法加载,效果很好,绝对是要走的路,但我绝对不能告诉你为什么哈哈
      • 由于填充计入对象大小 - 这可用于使 iframe 通常更大(因为它是绝对定位的)。百分比值与对象宽度相关,因此即使调整元素本身的大小,这也将保持纵横比不变。用文字解释有点困难,但我希望这会有所帮助?
      猜你喜欢
      • 2018-01-06
      • 1970-01-01
      • 2014-10-07
      • 1970-01-01
      • 2016-10-09
      • 2020-08-23
      • 2015-09-04
      • 2017-10-26
      • 2020-08-07
      相关资源
      最近更新 更多