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>