开发者

Scalable Background HTML CSS Javascript

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 somethin开发者_JAVA技巧g more compatible.

Many thanks,

Elliott


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.


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


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 ;)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜