Sunday, April 10, 2011

CSS trick to cover with perfect background width and height


There is one cool trick to fill place with background, even if their sizes different. Just use the code for css:
body {
background-image: url(bg.jpg);
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}

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

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.

Works in

  • Safari 3+
  • Chrome Whatever+
  • IE 9+
  • Opera 10+ (Opera 9.5 supported background-size but not the keywords)
  • Firefox 3.6+ (Firefox 4 supports non-vendor prefixed version)

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

The article can also mean: css tricks

No comments:

Post a Comment