在CSS中關於定位的內容是:
position:relative | absolute | static | fixed
static(靜態) 沒有特別的設定,遵循基本的定位規定,不能經過z-index進行層次分級,這是默認值。
relative(相對定位) 對象不可層疊、不脫離文檔流,參考自身靜態位置經過 top,bottom,left,right 定位,而且能夠經過z-index進行層次分級。
absolute(絕對定位) 脫離文檔流,經過 top,bottom,left,right 定位。選取其最近一個最有定位設置的父級對象進行絕對定位,若是對象的父級沒有設置定位屬性,absolute元素將以body座標原點進行定位,能夠經過z-index進行層次分級。
fixed(固定定位) 這裏所固定的參照對像是可視窗口而並不是是body或是父級元素,其老是固定在瀏覽器窗口的某個位置,而且不受滾動的影響,是絕對的座標定位。可經過z-index進行層次分級。
注:
CSS中定位的層疊分級:
z-index: auto | namber;
auto 聽從其父對象的定位
namber 無單位的整數值。可爲負數,默認值爲0,越大越靠上,值大的元素會覆蓋住值小的元素。
分析:
-
div1和div2因爲是absolute佈局,其位置徹底由left和top來決定,不受父元素的padding的影響,徹底脫離文檔流
-
div3和div4是relative佈局,其位置除了由left和top來決定外,還受父元素的padding以及文檔流的影響,好比,div4就受到了div3的影響,儘管其top和div3同樣都是0,可是卻顯示在div4的下面,由於div3在文檔流中,div4只能跟着文檔流,排在div3的下面
-
div5是fixed佈局,其位置始終是左上角,即便瀏覽器滾動,它仍是固定在左上角
-
關於z-index,若是不寫則默認值是0,上面的例子很好的說明了z-index的做用
-
absolute佈局,其參考點是最近的具備position屬性的元素,若是本例中將main div的position屬性去掉的話,總體佈局就會不同,這個時候,div1和div2的參考點是body
<html><head>
<style type="text/css">
body{margin:0px;padding:0px;line-height:100%;}
div
{
background-color:rgb(159, 206, 159);
width:95px;
height:95px;
margin: 0px 0px 1px 1px;
padding:0px;
/*display:inline-block;*/
letter-spacing:1px;
/* only for ie*/
*display:inline;
*zoom:1;
border:1px solid #ffffff;
border-radius:5px;
-moz-border-radius:5px; /* Old Firefox */
opacity:1;
text-align:center;
color:white;
}
#main{width:400px;height:300px;}
</style>
</head>
<body>
<div id="main" style="
position: relative;
margin: 50px;
padding: 80px;
">
<div id="div1" style="
position: absolute;
left: 83px;
top: 0px;
background-color: rgb(199, 219, 50);
">div1 absolute</div>
<div id="div2" style="
position: absolute; left: 0px;
top: 90px;
background-color: rgb(1, 214, 35);
z-index:10;
">div2 absolute z-index<br/>:10</div>
<div id="div3" style="
position: relative; left: 0px;
top: 0px;
background-color: rgb(23, 178, 238);
z-index:11
">div3 relative z-index:11</div>
<div id="div4" style="
position: relative; left: 0px;
top: 0px;
background-color: rgb(23, 178, 238);
z-index:0;
">div4 relative z-index:0</div>
<div id="div5" style="
position: fixed; left: 10px;
top: 10px;
background-color: rgb(229, 122, 238);
">div5 fixed</div>
</div>
</body></html>
請參見:http://www.cnblogs.com/jenry/archive/2007/07/15/818660.html