在写主题样式的时候经常会碰到用背景图铺满整个背景的需求,这里分享下使用方法
需要的效果
1、图片以背景的形式铺满整个屏幕,不留空白区域
2、保持图像的纵横比(图片不变形)
3、图片居中
4、不出现滚动条
5、多浏览器支持
以图片bg.jpg
为例
最简单,最高效的方法 CSS3.0
归功于css3.0
新增的一个属性background-size
,可以简单的实现这个效果,这里用fixed
和center
定位背景图,然后用background-size
来使图片铺满,具体css
如下
html {
background: url(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 支持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')";
如果你觉得上面的方法不是很满意,那试试下面这种
用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');
浏览器支持
- ie7+
- 绝大多数主流浏览器