2013-10-14 146 views
9

我想創建一個具有始終填充整個窗口的背景圖像的網站,即使內容可以垂直滾動。如何使用滾動內容的100%CSS背景圖片?

我創建了this JSFiddle使用background-size:cover將背景圖像縮放到窗口。

它的工作原理,只要裏面的div小於窗口。 如果垂直滾動,背景圖像不再填充頁面,而是顯示白色/灰色區域。

所以我的問題是:如何將100%的背景圖像與滾動內容相結合? 這是我的CSS:

html { 
    height: 100%; 
    margin:0px; 
    background-color:#999999; 
    background-image: url(http://s22.postimg.org/e03w9stjl/main_bg.png); 
    background-position:center; 
    background-repeat:no-repeat; 
    background-size: cover; 
} 
body { 
    min-height: 100%; 
    margin:0px; 
} 
#appcontainer { 
    position: absolute; 
    background-color: rgba(255, 255, 255, 0.7); 
    width:560px; height:2220px; 
    left:20px; top:20px; 
} 

和HTML:

<!DOCTYPE html> 
<html> 
<head></head> 
<body> 

    <div id="appcontainer"> 
     This div causes the background image to stop scaling to the page. 
    </div> 

</body> 
</html> 

回答

14

使用background-attachment: fixed;

Demo

html { 
    height: 100%; 
    margin:0px; 
    background: url(http://www.freegreatpicture.com/files/147/18380-hd-color-background-wallpaper.jpg) no-repeat center center; 
    background-size: cover; 
    background-attachment: fixed; 
} 

而且,我沒有得到爲什麼要包裝元素上使用position: absolute;,通常你應該使用position: relative;

+0

謝謝,它的工作現在:)爲什麼相對而不是絕對的使用? – Kokodoko

+0

@PietBinnenbocht這是lil詳細的定位概念,閱讀一些文章,你會得到我的觀點,爲什麼不使用絕對的,因爲你正在做的事似乎沒有任何需要使用絕對:) –

2
#appcontainer { 
     position: absolute; 
     background-color: rgba(255, 255, 255, 0.7); 
     background: url(images/bg.jpg) no-repeat center center fixed; 
     -webkit-background-size: cover; 
     -moz-background-size: cover; 
     -o-background-size: cover; 
     background-size: cover; 
     top: 0; 
     right 0; 
     left: 0; 
     bottom 0; 
    } 
+0

你錯過了右邊的分號和底部 – kofifus

5

添加到您的CSS:

background-attachment: fixed;