我希望我的背景图像拉伸和缩放取决于浏览器视口的大小。

我在Stack Overflow上看到过一些问题,比如拉伸和缩放CSS背景。它工作得很好,但我想使用背景放置图像,而不是使用img标签。

在其中放置了一个img标签,然后用CSS向img标签致敬。

width:100%; height:100%;

它的工作,但这个问题有点老了,并指出在css3调整背景图像的大小将工作得很好。我已经尝试了第一个例子,但它不适合我。

是否有一个好的方法来做背景图像声明?


当前回答

这是由CSS技巧解释的:完美的全页面背景图像

演示:https://css-tricks.com/examples/FullPageBackgroundImage/progressive.php

代码:

body {
  background: url(images/myBackground.jpg) no-repeat center center fixed;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
}

其他回答

实际上,您可以使用img标记实现与背景图像相同的效果。你只需要将它的z-index设置得比其他所有东西都低,设置position:absolute,并为前景中的每个盒子使用透明背景。

您可以将这个类添加到CSS文件中。

.stretch {
    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浏览器等等 Internet Explorer 9或更高版本 Opera 10或更高版本(Opera 9.5支持background-size,但不支持关键字) Firefox 3.6或更高版本(Firefox 4支持非供应商前缀版本)

这是由CSS技巧解释的:完美的全页面背景图像

演示:https://css-tricks.com/examples/FullPageBackgroundImage/progressive.php

代码:

body {
  background: url(images/myBackground.jpg) no-repeat center center fixed;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
}

使用下面的CSS:

background: url('img.png') no-repeat; 
background-size: 100%;

您希望仅使用一个图像就实现这一点吗?因为你可以用两张图片来做一个类似的背景拉伸。比如PNG图片。

我以前做过这个,并不难。此外,我认为拉伸只会损害背景的质量。如果你添加一个巨大的图像,它会减慢缓慢的电脑和浏览器。