Wednesday, October 2, 2013

Full Page Background



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

CSS-Only Technique #2

One rather simple way to handle this is to put an inline image on the page, fixed position it to the upper left, and give it a min-width and min-height of 100%, preserving it's aspect ratio.
<img src="images/bg.jpg" id="bg" alt="">
#bg {
  position: fixed; 
  top: 0; 
  left: 0; 
 
  /* Preserve aspet ratio */
  min-width: 100%;
  min-height: 100%;
}
However, this doesn't center the image and that's a pretty common desire here... So, we can fix that by wrapping the image in a div. That div we'll make twice as big as the browser window. Then the image will be placed, still preserving it's aspect ratio and covering the visible browser window, and the dead center of that.
<div id="bg">
  <img src="images/bg.jpg" alt="">
</div>
#bg {
  position: fixed; 
  top: -50%; 
  left: -50%; 
  width: 200%; 
  height: 200%;
}
#bg img {
  position: absolute; 
  top: 0; 
  left: 0; 
  right: 0; 
  bottom: 0; 
  margin: auto; 
  min-width: 50%;
  min-height: 50%;
}
Credit to Corey Worrell for the concept on this one.
Works in:
  • Safari / Chrome / Firefox (didn't test very far back, but recent versions are fine)
  • IE 8+
  • Opera (any version) and IE both fail in the same way (wrongly positioned, not sure why)
  • Peter VanWylen wrote in to say that if you add the image via JavaScript, the img needs to have width: auto; and height: auto; to work in IE 8, 9, or 10.


No comments:

Post a Comment