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


当前回答

添加背景附件行:

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

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

其他回答

一句话:不。拉伸图像的唯一方法是使用<img>标记。你必须要有创造力。

在2008年,当答案写出来的时候,这曾经是正确的。如今,现代浏览器支持背景大小,这就解决了这个问题。注意,IE8不支持它。

在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感兴趣。

我想指出,这相当于做:

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

添加背景附件行:

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

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

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