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/