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


当前回答

我想指出,这相当于做:

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

其他回答

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

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

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

试试这个

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;
}

使用CSS 3属性background-size:

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

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

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

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

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