对于div的绝对定位一直觉得margin属性是无效的,只是经过top,left,bottom,right定位,然而今天的却发现不是这样的,因而对其作了些实验:css
使用的HTML原始测试文件: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:app
- <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不进行定义,则以下图:ui
- .bottom{
- width:200px;
- height:40px;
- position:absolute;
- background:#0F0;
- }

则绝对定位元素对位参照上层父级元素。spa
- .bottom{
- width:200px;
- height:40px;
- position:absolute;
- background:#0F0;
- top:30px;
- margin-top:-30px;
- }
上面代码的显示和上面的图是同样的。top的值是top和margin-top相加的值xml
下面的也是:htm
咱们把margin-top的值改成30px;it
则是下面的图:io

说明上面的推断可能正确,总的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中也一样适用:

如今咱们能够获得结论了,当绝对定位块和上层相对定位(或绝对定位)中间夹着一层标准流(或浮动)的块时:
一、只使用left等定位是按照上层相对定位(或绝对定位)的边界进行定位
二、只使用margin相关属性定位时按照上层标准流(或浮动)块的边界进行定位
三、当同时使用二者时则按照上层相对定位(或绝对定位)的边界进行定位,而且距离值为二者的相加值
补充一点:
元素的上下和左右分别对应于哪层块互不干扰。
引伸应用:
上述特色能够用来无hack地定位居中元素:
具体以下:
- #con{
- position:absolute;
- left:50%;
- width:760px;
- margin-left:-380px;
- }
上面的代码就是应用了得出的观点的第三点执行的,并且这种上面的定位方式是彻底遵循Css原则的无hack的模式