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


当前回答

试试这个

http://jsfiddle.net/5LZ55/4/

body
{ 
    background: url(http://p1.pichost.me/i/40/1639647.jpg) no-repeat fixed; 
    background-size: cover;
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
}

其他回答

使用border-image: yourimage属性来设置你的图像,并将其放大到屏幕或窗口的整个边界。

我想指出,这相当于做:

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

这就是我做的。在拉伸类中,我简单地将高度更改为auto。这样,你的背景图片总是与屏幕宽度相同,高度也总是有合适的大小。

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

.stretch {
    width:100%;
    height:auto;
}
.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/

在CSS3中使用background-size属性:

.class {
     background-image: url(bg.gif);
     background-size: 100%;
}

编辑:Modernizr支持检测背景大小支持。您可以使用编写的JavaScript解决方案来工作,无论您需要它,并在不支持时动态加载它。这将保持代码的可维护性,而无需诉诸于某些浏览器的侵入性CSS hack。

就我个人而言,我使用jQuery脚本来处理它,它是imgsizer的一个改编。正如我现在所做的大多数设计一样,我在设备之间使用宽度%的流体布局,其中一个循环有轻微的适应(考虑到大小并不总是100%):

for (var i = 0; i < images.length; i++) {
    var image = images[i],
        width = String(image.currentStyle.width);

    if (width.indexOf('%') == -1) {
        continue;
    }

    image.origWidth = image.offsetWidth;
    image.origHeight = image.offsetHeight;

    imgCache.push(image);
    c.ieAlpha(image);
    image.style.width = width;
}

编辑: 你可能也对jQuery CSS3 Finaliz[s]e感兴趣。