是否有一种方法来获得CSS的背景拉伸或缩放以填充它的容器?


当前回答

.style1 {
        background: url(images/bg.jpg) no-repeat center center fixed;
        -webkit-background-size: cover;
        -moz-background-size: cover;
        -o-background-size: cover;
        background-size: cover;
}

适用于:

Safari 3 + Chrome无论+ IE 9 + Opera 10+ (Opera 9.5支持背景大小,但不支持关键字) Firefox 3.6+ (Firefox 4支持非供应商前缀版本)

此外,您可以尝试使用ie解决方案

    filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src='.myBackground.jpg', sizingMethod='scale');
    -ms-filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='myBackground.jpg', sizingMethod='scale')";
    zoom:1;

这篇文章的作者是Chris Coyier http://css-tricks.com/perfect-full-page-background-image/

其他回答

使用CSS缩放图像是不太可能的,但是可以通过以下方式实现类似的效果。

使用下面的标记:

<div id="background">
    <img src="img.jpg" class="stretch" alt="" />
</div>

使用以下CSS:

#background {
    width: 100%; 
    height: 100%; 
    position: absolute; 
    left: 0px; 
    top: 0px; 
    z-index: 0;
}

.stretch {
    width:100%;
    height:100%;
}

你该结束了!

为了将图像缩放为“完全出血”并保持纵横比,你可以这样做:

.stretch { min-width:100%; min-height:100%; width:auto; height:auto; }

它的效果非常好!然而,如果裁剪一个维度,它将只在图像的一侧裁剪,而不是在两侧均匀裁剪(并居中)。我已经在Firefox、Webkit和Internet Explorer 8中测试了它。

使用CSS 3属性background-size:

#my_container {
    background-size: 100% auto; /* width and height, can be %, px or whatever. */
}

自2012年以来,这一功能可用于现代浏览器。

目前还没有。它将在CSS 3中可用,但要在大多数浏览器中实现还需要一段时间。

SolidSmile作弊的另一个技巧是通过设置宽度和自动设置高度来缩放(按比例重新调整大小)。

Ex:

#background {
    width: 500px;
    height: auto;
    position: absolute; 
    left: 0px; 
    top: 0px; 
    z-index: 0;
}

我想指出,这相当于做:

html { width: 100%; height: 100%; }
body { width: 100%; height: 100%; /* Add background image or gradient to stretch here. */}