2013-10-14 62 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;