Stretch and scale CSS background

有没有办法在CSS中获得背景以伸展或缩放以填充其容器?


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')";

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.


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.

链接地址: http://www.djcxy.com/p/4816.html

上一篇: 何时使用IMG与CSS背景

下一篇: 拉伸和缩放CSS背景