The W3C CSS Background and Borders Module Level 3 (currently a working draft) defines the background-size property that fits our requirements. Interesting values (to cite the W3C specs) are:
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.
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.
The background-size property is already supported by Firefox 3.6 (using the -moz prefix; Firefox 4 will use the regular CSS3 property), Chrome 5, Safari 5, and Opera 10.54; and it will be included in Internet Explorer 9 (it’s already available in Preview 3). Older Webkit and Opera versions already support the background-size property, however these implementations are based on a previous draft which did not include the contain and cover keywords.
The downside of this method is that there is no background property available to set a minimum width or height. When one resizes the browser window to a very small width or height, the background image will rescale to a very small size, an often-undesired behavior.
The W3C CSS3 Media Queries Module (a candidate recommendation) defines conditional rules that only apply within certain width or height ranges. This enables us to implement background scaling from a minimal width and height and on. Media queries are supported by Firefox 3.5, Chrome, Safari 3, and Opera 7, and will also be included in Internet Explorer 9.
By adding the following style rules we tell the browser that we don’t want a background image to scale smaller than 1024x768 pixels:
body { background: #000 url(myBackground_1280x960.jpg) center center fixed no-repeat; -moz-background-size: cover; background-size: cover; } @media only all and (max-width: 1024px) and (max-height: 768px) { body { -moz-background-size: 1024px 768px; background-size: 1024px 768px; } }