在IE8中拉伸背景图片

6

我想将背景图片拉伸到父级div的100%宽度和高度。当然,background-size在IE8中不受支持。我尝试了以下代码,但它不起作用。

.box:before {
    background: url(images/body_background2.png) no-repeat;
    display: block;
    position: absolute;
    z-index: -1;
    height: 100%;
    width: 100%;
    content: '';
}
7个回答

12

使用带有 position:fixed;top:0;left:0;width:100%;height:100%; 和负的 z-index<img>。很遗憾,仅使用 CSS 无法在 IE 8 中实现此行为。

查看以下文章以获取更多信息:如何在网页中拉伸背景图像.

如果您想要将图像用作给定的 <div> 的背景,请尝试以下方法:

<div class="fullbackground">
    <img class="fullbackground" src="yourImageSrc" />
</div>
.fullbackground{
    position:relative;
}
img.fullbackground{
    position:absolute;
    z-index:-1;
    top:0;
    left:0;
    width:100%; /* alternative: right:0; */
    height:100%; /* alternative: bottom:0; */
}

谢谢!对于整个页面来说效果很好。但是我正在尝试仅将其应用于页面中间的一个div。 - Mosaic
很酷,我多次看到那篇文章,却没有注意到后面的部分。 - Mosaic
@user1157575:看文章后面的部分;)-我更新了我的答案。如果<div>已经定位,您的容器上不需要使用class=fullbackground - Zeta
只是顺便提一下,如果您想让图像具有响应性(即在页面宽度小于图像宽度时不压缩图像),那么只需添加 min-width: {whatever-width-the-image-is},高度也是同理。 - John Ruddell

3

这并不会使它成为一个次等解决方案 ;) 所以+1 - anddoutoi
我的问题不是针对整个页面,只是针对一个div。 - Mosaic
嗯?那又怎样?你应该能够使用相同的技术。 - anddoutoi

2
使用AlphaImageLoader过滤器并将sizingMethod设置为scale似乎可以解决问题,根据完美全页背景图像的说法。

1

HTML:

<img class="fullscreen" src="fullscreen.jpg" />

CSS:

img.fullscreen {
  border:     0;
  height:     auto;
  left:       0;
  min-height: 100%;
  min-width:  1024px;
  padding:    0;
  position:   fixed;
  top:        0;
  width:      100%;
  z-index:    -1001;
}

1
请看https://github.com/louisremi/background-size-polyfill,这是我的团队中的另一位成员为解决同样问题而发现的不错的插件。
一旦您将脚本包含到您的解决方案中,请在相关的CSS类中添加以下行以及您可能希望添加的任何其他大小/定位属性。 -ms-behavior: url(/scripts/backgroundsize.min.htc); 我们已经将其实现于全宽图像和小部件背景,并且效果非常好。

0

我将AlfaImageLoader滤镜与css3的background-size属性结合使用,能在所有浏览器上运行。以下是我的实现方法。

background : url('../images/background.jpg') no-repeat ;
background-size: 100%;
filter: progid:DXImageTransform.Microsoft.AlphaImageLoader
            (src='images/background.jpg',sizingMethod='scale');

顺便提一下,在这种方法中,您需要将背景图像放置在包装器div中。


0

这个(demo)可以解决问题(来自http://css-tricks.com/perfect-full-page-background-image/的可消化版本的仅使用CSS技巧#2):

<div class="background-size_cover">
  <img src="images/body_background2.png">
</div>

并且

.background-size_cover {
  top: -50%;
  left: -50%;
  width: 200%;
  height: 200%;
  position: relative;
}
.background-size_cover img {
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  margin: auto;
  min-width: 50%;
  min-height: 50%;
  position: absolute;
}

您需要确保父级 div 具有 overflow: hidden;,除了具有您想要拉伸以适应其中的图像的任何尺寸。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接