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


当前回答

.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/

其他回答

一句话:不。拉伸图像的唯一方法是使用<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做到这一点…

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

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

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

试试文章的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%;
}