Background Image Scaling While Maintaining Aspect Ratio

Sev picture Sev · Apr 6, 2011 · Viewed 54.7k times · Source

I would like to have images for my background that change automatically like a slide show. But I would like the images to fill the background no matter what size the browser window is...and if it is scaled down, the aspect ratio of the image does not change.

Here is an example of what I'm trying to do:

http://www.thesixtyone.com/

How can I accomplish these tasks? Any help will be much appreciated.

Answer

drudge picture drudge · Apr 6, 2011

With CSS3, you would use background-size property.

background-size: contain; Scale the image, while preserving its intrinsic aspect ratio (if any), to the largest size such that both its width and its height can fit inside the background positioning area.

Contain always fits the entire image within your viewport, leaving opaque borders on either the top-bottom or the left-right whenever the ratio of the background image and browser window are not the same.

background-size: cover; Scale the image, while preserving its intrinsic aspect ratio (if any), to the smallest size such that both its width and its height can completely cover the background positioning area.

Cover always fills the browser window, cutting off some hair or ears in the process, which is what I personally prefer for most cases. You can control how your image is aligned within the viewport by using the background-position property.