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

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

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

width:100%; height:100%;

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

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


当前回答

我希望将背景图像居中并缩放,而不是将其拉伸到整个页面,并且我希望保持纵横比。这对我来说很管用,多亏了其他答案中提出的变化:

内联图片:------------------------

<div id="background">
    <img src="img.jpg" class="stretch" alt="" />
</div>

CSS ----------------------------------

html {
    height:100%;
}

#background {
    text-align: center;
    width: 100%; 
    height: 100%; 
    position: fixed;
    left: 0px; 
    top: 0px; 
    z-index: -1;
}

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

其他回答

使用我提到的代码…

HTML

<div id="background">
    <img src="img.jpg" class="stretch" alt="" />
</div>

CSS

#background {
    width: 100%; 
    height: 100%; 
    position: fixed; 
    left: 0px; 
    top: 0px; 
    z-index: -1; /* Ensure div tag stays behind content; -999 might work, too. */
}

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

这就产生了预期的效果:只有内容会滚动,背景不会滚动。

背景图像根据浏览器视口的大小调整为任何屏幕大小。当内容不适合浏览器视口时,用户需要滚动页面,当内容滚动时,背景图像在视口中保持固定。

使用css3,这似乎会容易得多。

您可以将这个类添加到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支持非供应商前缀版本)

我使用了background- x CSS属性的组合来实现理想的缩放背景图像。

background-size: cover;
background-repeat: no-repeat;
background-position: center;
background-attachment: fixed;

这使得背景总是覆盖整个浏览器窗口,并在缩放时保持居中。

谢谢!

但后来在谷歌Chrome和Safari浏览器上就不行了(拉伸可以,但图片的高度只有2毫米!),直到有人告诉我缺少什么:

尝试设置高度:auto;min-height:100%;

所以根据你的身高来改变:100%;线,给:

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

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

就在新添加的代码之前,我在Drupal Tendu themes style.css中有这样的代码:

html,身体{高度:100%;} 页面#{背景:# ffffff;高度:汽车!重要;高度:100%,最低高度:100%;位置:相对;}

然后,我必须在Drupal中创建一个新的块,同时添加class=stretch:

< img alt=“” class=“stretch” src=“pic.url” />

只是用Drupal块中的编辑器复制图片是行不通的;必须将编辑器更改为非格式化文本。

下面的方法对我很有效。

.back-ground {
   background-image: url("../assets/background.png");
   background-size: 100vw 100vh;
}

这可以在不同的维度上覆盖整个背景