关于html:嵌入YouTube视频时的自动高度?

Automatic height when embedding a YouTube video?

我已经在网站上嵌入了YouTube视频,但麻烦的是我需要根据视频的宽度和纵横比自动调整高度。 因此,如果我的宽度是1280,那么如果视频是16:9,则我的高度应该是720。
我尝试使用" VW"和" VH"单元,但这些似乎不适用于iframe。 我的宽度已经按比例设置。

我的代码如下:

1
<iframe style="margin-right: 1%; margin-left: 1%;" width="98%" height="" src="https://www.youtube.com/embed/HwzQbfde-kE" frameborder="0"></iframe>

您可以通过此代码解决它。 现场示例链接

CSS:

1
2
3
4
5
6
7
8
9
10
11
12
.video-container {
    position: relative;
    padding-bottom: 56.25%; /* 16:9 */
    height: 0;
}
.video-container iframe {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
}

HTML示例

1
    <iframe width="560" height="315" src="https://www.youtube.com/embed/_TyJeKKQh-s?controls=0" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>


我能够在样式元素的宽度和高度上使用vw来生成自适应iframe大小,因为我知道我希望元素使用的水平宽度量,然后根据宽度和知识计算高度 视频是16:9。 如果您希望视频占用屏幕尺寸893px以上的水平空间的45%,否则消耗90%的水平空间,则:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
.embedded-video-16-9 {
  width:  90vw;
  height: 50.625vw; /* 90*9/16 */
  margin-left: 5vw;
  margin-right: 5vw;
}

@media (min-width: 893px) {
  .embedded-video-16-9 {
    width: 45vw;
    height: 25.3125vw; /* 45*9/16 */
    margin-left: 2vw;
    margin-right: 2vw
  }
}

像这样使用:

1
2
3
4
5
6
<iframe
  class="embedded-video-16-9"
  src="https://www.youtube.com/embed/_TyJeKKQh-s?controls=0"
  frameborder="0"
  allowfullscreen=""
></iframe>