全尺寸 YouTube 视频,所有宽高比,仅 CSS
TL:DR - 工作小提琴 https://jsfiddle.net/ohepworthbell/k72hbytr/
作为对 @Hinrich 答案的更新/改进,我创建了一个仅 CSS 的缩放器,适用于所有宽高比 - 甚至是极端的宽高比。 iframe 不是过度补偿宽度以适应大多数屏幕尺寸,而是使用vw
and vh
并使用 CSS 进行偏移transform
属性(相对于元素而不是父元素的偏移)。
大多数浏览器(IE9+ 和所有常青浏览器 AFAIK)都支持vw
and vh
单位,以及transform
s,所以这应该适用于几乎所有浏览器无需 JavaScript.
.video-background {
position: relative;
overflow: hidden;
width: 100vw;
height: 100vh;
}
.video-background iframe {
position: absolute;
top: 50%;
left: 50%;
width: 100vw;
height: 100vh;
transform: translate(-50%, -50%);
}
@media (min-aspect-ratio: 16/9) {
.video-background iframe {
/* height = 100 * (9 / 16) = 56.25 */
height: 56.25vw;
}
}
@media (max-aspect-ratio: 16/9) {
.video-background iframe {
/* width = 100 / (9 / 16) = 177.777777 */
width: 177.78vh;
}
}
<div class="video-background">
<iframe src="https://www.youtube.com/embed/biWk-QLWY7U?controls=0&showinfo=0&rel=0&autoplay=1&loop=1&mute=1" frameborder="0" allowfullscreen></iframe>
</div>
使用 CSS 变量
对于那些使用 CSS 变量的人,您还可以这样做(小提琴) https://jsfiddle.net/ohepworthbell/62ktqs1j/,它允许您任意重用多个类名的大小:
:root {
--video-width: 100vw;
--video-height: 100vh;
}
@media (min-aspect-ratio: 16/9) {
:root {
--video-height: 56.25vw;
}
}
@media (max-aspect-ratio: 16/9) {
:root {
--video-width: 177.78vh;
}
}
.video-background {
position: relative;
overflow: hidden;
width: 100vw;
height: 100vh;
}
.video-background iframe {
position: absolute;
top: 50%;
left: 50%;
width: var(--video-width);
height: var(--video-height);
transform: translate(-50%, -50%);
}