在Web网页前端开发中使用background-attachment:fixed;样式设置背景图片固定时发现苹果手机浏览器Safari不支持CSS属性background-attachment,这着实有点意外,毕竟background-attachment是个比较老标准的CSS属性。既然不支持,那就只能使用替代方案了,比如可以通过固定定位样式position:fixed;实现。
代码很简单,CSS基础牢固的都能想到或者理解思路。
HTML代码:
<div class="parent"> <div class="fixed" style="background-image:url(bg.jpg);"></div> </div>
CSS代码:
.parent {
position:relative;
overflow:hidden;
}
.parent .fixed {
position:fixed;
left:0;
top:0;
width:100%;
height:100%;
background:no-repeat center center;
background-size:cover;
z-index:0;
}
如果想弄减少一个div元素,也可以使用伪元素:before或:after,如:
.parent {
position:relative;
overflow:hidden;
}
.parent:before {
position:fixed;
left:0;
top:0;
width:100%;
height:100%;
background:url(bg.jpg) no-repeat center center;
background-size:cover;
z-index:0;
display:block;
content:'';
}
这样就可以省掉<div class="fixed" style="background-image:url(bg.jpg);"></div>这块代码了。