Stretch and scale CSS background
Use the CSS 3 property background-size
:
#my_container {
background-size: 100% auto; /* width and height, can be %, px or whatever. */
}
This is available for modern browsers, since 2012.
For modern browsers, you can accomplish this by using background-size
:
body {
background-image: url(bg.jpg);
background-size: cover;
}
cover
means stretching the image either vertically or horizontally so it never tiles/repeats.
That would work for Safari 3 (or later), Chrome, Opera 10+, Firefox 3.6+, and Internet Explorer 9 (or later).
For it to work with lower verions of Internet Explorer, try these CSS:
filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src='.myBackground.jpg', sizingMethod='scale');
-ms-filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='myBackground.jpg', sizingMethod='scale')";
Scaling an image with CSS is not quite possible, but a similar effect can be achieved in the following manner, though.
Use this markup:
<div id="background">
<img src="img.jpg" class="stretch" alt="" />
</div>
with the following CSS:
#background {
width: 100%;
height: 100%;
position: absolute;
left: 0px;
top: 0px;
z-index: 0;
}
.stretch {
width:100%;
height:100%;
}
and you should be done!
In order to scale the image to be "full bleed" and maintain the aspect ratio, you can do this instead:
.stretch { min-width:100%; min-height:100%; width:auto; height:auto; }
It works out quite nicely! If one dimension is cropped, however, it will be cropped on only one side of the image, rather than being evenly cropped on both sides (and centered). I've tested it in Firefox, Webkit, and Internet Explorer 8.