嵌入YouTube视频时的自动高度?

问题描述 投票:8回答:2

我在我的网站上嵌入了一个YouTube视频但问题是我需要根据视频的宽度和宽高比自动调整高度。因此,如果我的宽度是1280,如果视频是16:9,我的身高应该是720。我尝试使用'大众'和'VH'单位,但这些似乎不适用于iframe。我的宽度已按比例设定。

我的代码如下:

<iframe style="margin-right: 1%; margin-left: 1%;" width="98%" height="" src="https://www.youtube.com/embed/HwzQbfde-kE" frameborder="0"></iframe>
html css video youtube
2个回答
8
投票

问题由Reddit用户'mr_bacon_pants'here.解决


4
投票

您可以通过此代码解决它。 Live example Link

CSS:

.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

<div class="video-container">
    <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>
    </div>
© www.soinside.com 2019 - 2024. All rights reserved.