对于div的绝对定位一直以为margin属性是无效的,只是通过top,left,bottom,right定位,然而今天的却发现不是这样的,于是对其做了些实验:
使用的HTML原始测试文件:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>test</title>
</head>
<body>
<div class="wrapper">
<div class="box">
<div class="bottom"></div>
</div>
</div>
</body>
</html>
原始的测试css:
<style>
*{
margin:0;
padding:0;
}
.wrapper{
width:400px;
overflow:hidden;
background:#000;
margin:20px auto;
position:relative;
}
.box{
width:200px;
height:400px;
background:#F00;
margin-left:40px;
}
.bottom{
width:200px;
height:40px;
position:absolute;
background:#0F0;
top:0;
left:0;
}
</style>
上面的图是普通的定义了top和left的,绝对定位的元素在父元素中寻找相对或绝对定位的并进行定位。
而要是这top和left不进行定义,则如下图:
.bottom{
width:200px;
height:40px;
position:absolute;
background:#0F0;
}
则绝对定位元素对位参照上层父级元素。
.bottom{
width:200px;
height:40px;
position:absolute;
background:#0F0;
top:30px;
margin-top:-30px;
}
上面代码的显示和上面的图是一样的。top的值是top和margin-top相加的值
下面的也是:
我们把margin-top的值改为30px;
则是下面的图:
说明上面的推断可能正确,总的top值是两个值的叠加。
下面我们用left方向来说明一下中间的.box的margin值对定位的作用:
.bottom{
width:200px;
height:40px;
position:absolute;
background:#0F0;
top:30px;
margin-top:30px;
left:20px;
}
单单是left定位的话很容易猜到下图:
而用单单用margin-left呢?
.bottom{
width:200px;
height:40px;
position:absolute;
background:#0F0;
top:30px;
margin-top:30px;
margin-left:20px;
}
可以看到它是根据未用position定位的父级元素的边界进行margin定位的。
如果margin和left一起出现呢?
为了和前面的区别开来,我采用left:10px
.bottom{
width:200px;
height:40px;
position:absolute;
background:#0F0;
top:30px;
margin-top:30px;
margin-left:20px;
left:10px;
}
可以看到绿色的块元素左溢出红块,以为现在的left值为30px。
这个在IE6中也同样适用:
现在我们可以得到结论了,当绝对定位块和上层相对定位(或绝对定位)中间夹着一层标准流(或浮动)的块时:
1、只使用left等定位是按照上层相对定位(或绝对定位)的边界进行定位
2、只使用margin相关属性定位时按照上层标准流(或浮动)块的边界进行定位
3、当同时使用两者时则按照上层相对定位(或绝对定位)的边界进行定位,并且距离值为两者的相加值
补充一点:
元素的上下和左右分别对应于哪层块互不干扰。
引申应用:
上述特点可以用来无hack地定位居中元素:
具体如下:
#con{
position:absolute;
left:50%;
width:760px;
margin-left:-380px;
}
上面的代码就是应用了得出的观点的第三点执行的,而且这种上面的定位方式是完全遵循Css原则的无hack的模式