周末朋友发出江湖救急的消息,说他有个莫名其妙的bug搞不定了,于是我让他把bug的代码发过来看看。
他的需求是绝对居中,代码是这样的
如果你已经看出问题了,那么这篇文章就可以不用看了。如果你觉得这段代码没问题,那么可以继续探讨。
大多数时候我们做一个块的居中,写法都是这样的
看出区别了吧,区别就在于,margin是负的具体像素,定位是百分比。而出bug的写法刚好相反。乍一看这是没啥区别的,甚至我也曾经想当然的认为这两种写法是一样的。
这就是典型的知其然不知其所以然。
我们看一下W3.org上关于margin-top的说明:
关键就是这里
也就是说,只要margin的值是百分比,那么,他的基数就只会是父容器的宽度,比如父容器宽100PX,那么margin-top:50% 就是50px,无论父容器高是多少,都跟’margin-top’, ‘margin-bottom’的百分比值无关。
来个demo,这个是有问题的写法
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>无标题文档</title>
<style type="text/css">
.wrap{
width:300px;
height:1000px;
margin:20px auto;
border:#f1f1f1 1px solid;
}
.box{
width:100px;
height:100px;
background:#ff6600;
position:relative;
top:-50px;
left:-50px;
margin-top:50%;
margin-left:50%;
}
</style>
</head>
<body>
<div class="wrap">
<div class="box"></div>
</div>
</body>
</html>
提示:你可以先修改部分代码再运行。
然后来个正确的写法
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>无标题文档</title>
<style type="text/css">
.wrap{
width:300px;
height:1000px;
margin:20px auto;
border:#f1f1f1 1px solid;
}
.box{
width:100px;
height:100px;
background:#ff6600;
position:relative;
top:50%;
left:50%;
margin-top:-50px;
margin-left:-50px;
}
</style>
</head>
<body>
<div class="wrap">
<div class="box"></div>
</div>
</body>
</html>
提示:你可以先修改部分代码再运行。
需要注意的是,绝对定位的元素margin-top的百分比值低版本webkit下和其他浏览器表现不一,这个可以自己写几个demo试试看吧……..