我正在创建一个相对(不是固定(YouTube提供视频源的视频背景。
主要的父容器的最大高度为600px,但是这样做,YouTube视频的底部被切断了。是否有任何方法可以将600px的最大高度应用于iframe,但要保持宽度和响应速度?
html
<div id="video-container">
<div class='embed-container'>
<iframe src='https://www.youtube.com/embed/YOPnzvSrZd4?mute=1&controls=0&showinfo=0&rel=0&autoplay=1&loop=1&playlist=YOPnzvSrZd4&start=0' frameborder='0' allowfullscreen>
</iframe>
</div>
<div class="video-area">
<div class="video-table">
<div class="video-cell">{video-area:content}</div>
</div>
</div>
</div>
CSS
#video-container {
width: 100%;
overflow: hidden;
position: relative;
max-height: 600px;
}
.video-area {
position:absolute;
top: 0;
width: 100%;
height: 100%;
}
.video-table {
display:table;
width:100%;
height:100%;
max-width: 960px;
margin: 0 auto;
}
.video-cell {
display:table-cell;
vertical-align:middle;
padding:2em;
box-sizing: border-box;
}
.embed-container {
position: relative;
padding-bottom: 56.25%;
height: 0;
overflow: hidden;
max-width: 100%;
}
.embed-container iframe,
.embed-container object,
.embed-container embed {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
您可以通过将其高度设置为零来维护元素的长宽比,并将顶部或底部填充添加为百分比。当您第一次遇到它时,这似乎很奇怪,但是百分比填充了父元素宽度的一定百分比。
该视频似乎不是标准4:3或16:9,但更像2:3,因此我在父容器上设置了max-height:600px; max-width:900px;
。儿童容器的width:100%; height:0; padding-top:66.67%;
66.67%的数字为2/3(或600/900(,而不是一些魔术数字,因此您需要针对不同的长宽比进行调整。
就是这样。现在,该视频将填充小于900px宽的屏幕宽度,并保持其长宽比为66.67%。一旦超过900px宽度,视频就会受到限制,因此高度不会超过600px。我将margin:0 auto
放置为中心,您需要处理背景,以便在设计中看起来不错。
https://codepen.io/jason_b/pen/bylqod
我不确定这是否是黑客,但是当我遇到同一情况时,这对我有用。您可以使用flex属性在父母div内伸展孩子div。
对您的原始结构进行了一些更改:
#video-container {
width: 100%;
overflow: hidden;
position: relative;
display:flex;
height:600px;
-webkit-align-items: stretch;
-ms-align-items: stretch;
-moz-align-items: stretch;
-o-align-items: stretch;
align-items: stretch;
}
iframe
{
width:100%;
}
.video-area {
position:absolute;
top: 0;
width: 100%;
height: 100%;
}
.video-table {
display:table;
width:100%;
height:100%;
max-width: 960px;
margin: 0 auto;
}
.video-cell {
display:table-cell;
vertical-align:middle;
padding:2em;
color:white;
box-sizing: border-box;
}
.embed-container object,
.embed-container embed {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
<div id="video-container">
<iframe src='https://www.youtube.com/embed/YOPnzvSrZd4?mute=1&controls=0&showinfo=0&rel=0&autoplay=0&loop=1&playlist=YOPnzvSrZd4&start=0' frameborder='0' allowfullscreen>
</iframe>
<div class="video-area">
<div class="video-table">
<div class="video-cell">{video-area:content}</div>
</div>
</div>
</div>
iframe
{
height: -webkit-fill-available;
}
将此高度属性添加到您的iframe