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


当前回答

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

其他回答

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

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

使用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中测试了它。

对于现代浏览器,你可以通过使用background-size来实现:

body {
    background-image: url(bg.jpg);
    background-size: cover;
}

覆盖意味着垂直或水平拉伸图像,这样它就不会平铺/重复。

这适用于Safari 3(或更高版本)、Chrome、Opera 10+、Firefox 3.6+和Internet Explorer 9(或更高版本)。

为了让它在低版本的ie浏览器中工作,可以尝试以下CSS:

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

添加背景附件行:

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

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

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

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

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