15

I want to create a site with a background image that always fills the entire window, even if the content can scroll vertically.

I have created this JSFiddle using background-size:cover to scale the background-image to the window.

It works, as long as the divs inside are smaller than the window. If you scroll vertically, the background image does not fill the page anymore, and shows a white/grey area instead.

So my question is: how can I combine a 100% background image with scrolling content? This is my 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;
}

And 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>
Mr. Alien
  • 153,751
  • 34
  • 298
  • 278
Kokodoko
  • 26,167
  • 33
  • 120
  • 197

3 Answers3

25

Use 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;
}

Also, I didn't got why you are using position: absolute; on the wrapper element, generally you should be using position: relative;

Mr. Alien
  • 153,751
  • 34
  • 298
  • 278
  • Thanks, it's working now :) Why use relative instead of absolute? – Kokodoko Oct 14 '13 at 16:09
  • @PietBinnenbocht That's lil detailed positioning concept, read some articles and you will get my point, why not to use absolute, because the thing you are doing doesn't seem any need to use absolute :) – Mr. Alien Oct 14 '13 at 16:21
5

Add to your CSS:

background-attachment: fixed;
gvee
  • 16,732
  • 35
  • 50
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;
    }
im_benton
  • 2,541
  • 4
  • 21
  • 30