對於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的模式

