views:

407

answers:

3

Hi there,

Does anyone know of a way to have a background image scale to the dimensions of the browser window it is in? I know CSS3 allows for background width, but I need something more compatible.

Many thanks,

Elliott

+2  A: 

You cannot do it with a background-image, as it does not support sizing. You have to fake it by putting an img tag that stretches 100% in both directions and position it behind your content using absolute positioning and z-index. Something like this should work:

<body>
    <img class="bgimage" src="bgimage.jpg" />
    <div id="content">
        Your content here...
    </div>

And in CSS:

html, body {
    min-height: 100%;
}

.bgimage {
    position: absolute;
    z-index: -1;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
}

Haven't tested that, but that should give you some starters at least.

Tatu Ulmanen
This works awesome! I got rid of the height: 100% to prevent stretching of the image, and plan to add a fade at the bottom of the pic so the space below doesn't look too weird. Thanks for the help!
Elliott Bowles
+1  A: 

Here's the trick (from http://css-tricks.com/how-to-resizeable-background-image/)

Define your image like this:

<body id="page-body">
    <img class="source-image" src="images/image.jpg" alt="" />
</body>

and your CSS like this:

#img.source-image {
    width: 100%;
    position: absolute;
    top: 0;
    left: 0;
}
body {
    overflow: hidden;
}
Keltex
A: 

If you plan to have a very light screen it is fine.
But if you plan to use an image as a background for a crowded page, here are some reasons we abandoned this functionality:

  • Some browsers had a difficult time to render it fast: the first time, during the reflows and window resize.

  • For each picture we had to spend too much time to find a balance between file size and picture definition. It's not easy with the growing user base with big screens.

  • We even tried to load first a low-res version of the picture, while the big one was loading. It gave a very nice effect, but consuming even more browser resources

Once we dropped the stretched image, our app was fast again and we stopped procrastinating by playing with picture ;)

Mic
the site in question is very sparse on content, and it seemed to load at an acceptable rate. I could see how this would not be practicle on a big site though. Thanks for the pointers!
Elliott Bowles