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


当前回答

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

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

其他回答

试试文章的background-size。如果您使用以下所有选项,它将在除Internet Explorer之外的大多数浏览器中工作。

.foo {
    background-image: url(bg-image.png);
    -moz-background-size: 100% 100%;
    -o-background-size: 100% 100%;
    -webkit-background-size: 100% 100%; 
    background-size: 100% 100%;
} 

另一个很好的解决方案是robbin的Backstretch,它可以应用于页面的主体或任何元素- http://srobbin.com/jquery-plugins/backstretch/

试试这个

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

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

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

定义“延伸和规模”…

If you've got a bitmap format, it's generally not great (graphically speaking) to stretch it and pull it about. You can use repeatable patterns to give the illusion of the same effect. For instance if you have a gradient that gets lighter towards the bottom of the page, then you would use a graphic that's a single pixel wide and the same height as your container (or preferably larger to account for scaling) and then tile it across the page. Likewise, if the gradient ran across the page, it would be one pixel high and wider than your container and repeated down the page.

通常,当容器增大或缩小时,为了给人一种它拉伸填充容器的错觉,您可以使图像比容器更大。任何重叠都不会显示在容器的边界之外。

If you want an effect that relies on something like a box with curved edges, then you would stick the left side of your box to the left side of your container with enough overlap that (within reason) no matter how large the container, it never runs out of background and then you layer an image of the right side of the box with curved edges and position it on the right of the container. Thus as the container shrinks or grows, the curved box effect appears to shrink or grow with it - it doesn't in fact, but it gives the illusion that is what's happening.

至于真正让图像随着容器一起缩小和增大,您需要使用一些分层技巧来使图像看起来像一个背景,并使用一些javascript来调整它与容器的大小。目前没有办法用CSS做到这一点…

如果你使用矢量图形,恐怕就超出了我的专业领域。