代码改变世界

网页背景图片Full Page Background Image

2013-04-18 22:35  youxin  阅读(530)  评论(0编辑  收藏  举报

The goal here is a background image on a website that covers the entire browser window at all times. Let's put some specifics on it:

  • Fills entire page with image, no white space
  • Scales image as needed
  • Retains image proportions (aspect ratio)
  • Image is centered on page
  • Does not cause scrollbars
  • As cross-browser compatible as possible
  • Isn't some fancy shenanigans like Flash

Awesome, Easy, Progressive CSS3 Way

We can do this purely through CSS thanks to the background-size property now in CSS3. We'll use the html element (better than body as it's always at least the height of the browser window). We set a fixed and centered background on it, then adjust it's size using background-size set to the cover keyword.

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

在chrome中好像不加background-size:也可以。

另外的几种方法,参见:

http://css-tricks.com/perfect-full-page-background-image/