写主题样式的时候经常会碰到用背景图铺满整个背景的需求,这里分享下使用方法

需要的效果

  1. 图片以背景的形式铺满整个屏幕,不留空白区域
  2. 保持图像的纵横比(图片不变形)
  3. 图片居中
  4. 不出现滚动条
  5. 多浏览器支持

以图片bg.jpg为例

方法一、最简单,最高效的方法 CSS3.0

归功于css3.0新增的一个属性background-size,可以简单的实现这个效果,这里用fixed和center定位背景图,然后用background-size来使图片铺满,具体css如下

html {
background: url('../../../resources/images/welcome.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 支持background-size属性 但是不支持cover)
  • Firefox 3.6+

这里你会发现ie8及以下版本不支持,这些蛋疼浏览器则需要添加下面的css来设置兼容

filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src='.bg.jpg', sizingMethod='scale');
-ms-filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='bg.jpg', sizingMethod='scale')";

 

这个用滤镜来兼容的写法并不是很完美,首先是图片路径,这里只能是相对于根目录的路径,或者用绝对路径;然后是图片纵横比改变了,是拉伸铺满的形式。尽管如此,总比留空白好多了吧(如果背景图bg.jpg的宽高够大,则可以不用这段,变成简单的平铺,比图片变形效果好写,大家可以尝试下)

如果你觉得上面的方法不是很满意,那试试下面这种

方法二、

用img形式来实现背景平铺效果

首先在html中加入以下代码

<img src="bg.jpg" class="bg">

然后通过css来实现铺满效果(假设图片宽度1024px)

img.bg {
    min-height: 100%;
    min-width: 1024px;
    width: 100%;
    height: auto;
    position: fixed;
    top: 0;
    left: 0;
}

下面这个是为了屏幕小于1024px宽时,图片仍然能居中显示(注意上面假设的图片宽度)

 
@media screen and (max-width: 1024px) {
  img.bg {
    left: 50%;
    margin-left: -512px;
  }
}

 

兼容以下浏览器

  • 以下浏览器的所有版本: Safari / Chrome / Opera / Firefox
  • IE9+
  • IE 7/8: 平铺效果支持,但是在小于1024px的屏幕下居中效果失效

 

方法三、JQ模拟的方法html部分

  

<img src="bg.jpg" id="bg" alt="">

 

css部分

#bg { position: fixed; top: 0; left: 0; }
.bgwidth { width: 100%; }
.bgheight { height: 100%; }

 

js部分

$(window).load(function() {
    var theWindow = $(window),
        $bg = $("#bg"),
        aspectRatio = $bg.width() / $bg.height();
    function resizeBg() {
        if ( (theWindow.width() / theWindow.height()) < aspectRatio ) {
            $bg.removeClass().addClass('bgheight');
        } else {
            $bg.removeClass().addClass('bgwidth');
        }
    }
    theWindow.resize(resizeBg).trigger("resize");
});

支持浏览器

  • 以下浏览器的所有版本: Safari / Chrome / Opera / Firefox
  • IE7+

 

 

其实我自己一般用的是(因为够用了,咱不挑/其实上面的都是俺翻译过来的)

html部分

<div class="bg"></div>

 

css部分

.bg{
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: url(bg.jpg) no-repeat #000;
    background-size: cover;
    z-index: -1;
}

 

如果图片宽度没有达到1900px以上,我会加上ie的滤镜来支持ie8(这里我故意用了绝对路径,请知晓,代码长的我想砸了ie)

-ms-filter:"progid:DXImageTransform.Microsoft.AlphaImageLoader(src='.http://huilang.me/bg.jpg', sizingMethod='scale')";
filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='http://huilang.me/bg.jpg', sizingMethod='scale');