2012-06-27 48 views
3

我想要一個HTML5視頻的行爲完全像一個background: center center fixed; background-size: cover;元素而不使用JS(我知道有JS庫可以做到這一點)。我想通過媒體查詢(下面的例子假設您使用的是16/9視頻),根據窗口的縱橫比與視頻的縱橫比來設置寬度或高度爲100%。我現在要做的就是讓視頻水平或垂直居中。居中整個窗口視頻

任何幫助,將不勝感激。

@media screen and (max-aspect-ratio: 16/9) { 
    div#fixed video { 
    position: absolute; 
    height: 100%; 
    z-index: -100; 
    } 
} 

@media screen and (min-aspect-ratio: 16/9) { 
    div#fixed video { 
    position: absolute; 
    width: 100%; 
    z-index: -100; 
    } 
} 
+0

使用[居中圖像](http://stackoverflow.com/questions/11066145/how-to-auto-center-thumbnails-for-all-screen-sizes/11146227 #11146227)圖庫技術應用於單個視頻標籤。 –

回答

1
@media screen and (max-aspect-ratio: 16/9) { 
    div#fixed video { 
    position: absolute; 
    height: 100%; 
    z-index: -100; 
    top: 0; 
    bottom: 0; 
    margin:auto 0; 
    } 
} 

@media screen and (min-aspect-ratio: 16/9) { 
    div#fixed video { 
    position: absolute; 
    width: 100%; 
    z-index: -100; 
    text-align: left; 
    right: 0; 
    left: 0; 
    margin:0 auto; 
    } 
} 
1

你甚至都不需要媒體查詢來實現這一目標:)

試試這個:

#fixed { 
 
    position: relative; 
 
    height: 100vh; 
 
    z-index: 0; 
 
} 
 
#fixed video { 
 
    -webkit-transform: translateX(-50%) translateY(-50%); 
 
    -moz-transform: translateX(-50%) translateY(-50%); 
 
    -ms-transform: translateX(-50%) translateY(-50%); 
 
    -o-transform: translateX(-50%) translateY(-50%); 
 
    transform: translateX(-50%) translateY(-50%); 
 
    position: absolute; 
 
    top: 50%; 
 
    left: 50%; 
 
    min-width: 100%; 
 
    min-height: 100%; 
 
    width: auto; 
 
    height: auto; 
 
    z-index: -100; 
 
}
<div id="fixed"> 
 
\t <video autoplay loop class="bg-video"> 
 
\t \t <source src="https://d2v9y0dukr6mq2.cloudfront.net/video/preview/abstract-rainbow_wjpctkdes__PM.mp4" type="video/mp4"> 
 
\t </video> 
 
</div>

這裏有一個working fiddle example

希望它能幫助:)