Html – Scale background image so that it always keeps its aspect ratio and stays centered

backgroundcsshtmlresizescaling

I'd like to set a webpage background image to scale with the browser window so that it never loses its original aspect ratio (becomes stretched), and so that the image itself stays basically centered. After the window reaches a small enough size, I want the image to overflow (disappear) on both the left and right sides, not just the right side, as it does by default if the image is absolutely positioned.

Here is an example of what I'm doing right now: http://jsfiddle.net/S59EW/2/

#background img {
  position: absolute;
  min-height:100%;
  width: 100%;
  height: auto;
  top: 0;
  left: 0;
}

(The image has to be within a div positioned absolutely because of some javascript I'm using that applies to it.)

If you resize the jsfiddle window you'll see that the image keeps its aspect ratio only if you don't make the window too tall. Then the image is stretched vertically.

And if you remove "height: auto" you get the same thing except the image stops resizing after a certain point and disappears on the right/bottom sides but not on the top/left sides.

#background img {
  position: absolute;
  min-height:100%;
  width: 100%;
  top: 0;
  left: 0;
}

So, I need:

The background image to always occupy the entire window without scrollbars.
The image to always keep aspect ratio.
The image to overflow onto the left and right side after a certain browser size threshold, so that it remains basically centered.

Thanks everyone

Best Answer

You can set the div background through the CSS, that way the image will fill the div and the sides will cutoff when the div is resized smaller. This code will center the image within the div and cutoff at the edges when shrunken down:

HTML:

<div id="background"></div>

CSS:

#background {
    position: absolute;
    min-height:100%;
    width: 100%;
    height: auto;
    top: 0;
    left: 0;
    background: url(http://2.bp.blogspot.com/-ayEwJpMGTPQ/USqliwPWo1I/AAAAAAAAHtI/ab6NHVy0Q48/s1600/tree.jpg) no-repeat center center;
    -webkit-background-size: cover; /* Add in these */
    -moz-background-size: cover;    /* four lines to */
    -o-background-size: cover;      /* remove the white space*/
    background-size: cover;         /* around images */
}

JSFiddle

and full screen JSFiddle

Updated JSFiddle with background-size property included to remove white space

Updated full screen version

Updated with slideshow

Updated fullscreen with slideshow

You may need to play with the aspect ratio of the background photos in order to get the look you want.