CSS中 postion
是一個常用的屬性,position
有幾個屬性值:static、relative、absolute、fixed。每個屬性都有一定的特點,掌握了這些特點才能正確使用 position
屬性。
1.static
屬性默認值,對象遵循正常文檔流,top,bottom,left,right,z-index沒有作用。
2.relative
相對位置布局,對象遵循正常文檔流,占據正常文檔流的位置,但是根據top,bottom,left,right參數相對于正常位置相對偏移,就像是你坐火車去上廁所,雖然你離開了你原先的座位,但是你的座位本身還是占據空間的。相對位置布局的元素之間的層疊關系通過z-index屬性定義。
如果設置postion如下:
position: relative;
left: 20px;
top: 20px;
效果如下圖:
其中紅色虛線是不設置position為relative時的位置,紅色實現區域是按上面代碼設置position屬性值為relative,并且left和top屬性都為20px的結果,從上述結果中我們可以看到,偏移是相對其正常文檔流中的位置進行偏移的。
3.absolute
absolute,意味著“絕對”,可absolute的用法卻一點也不“絕對”,還是這個意思,理解的有偏差?不管怎樣,absolute的規則是確定的:
具有absolute屬性的塊元素,會向上一層一層尋找position不是static的第一個父元素,直到<html>父元素為止,如果存在這樣的父元素,left,top,right,bottom所設置的偏移量就是其相對于找到的父元素的偏移量,如果沒有,設置的偏移量以瀏覽器的左上角為基準。
如下代碼中,擁有absolute屬性的塊元素,其父元素position屬性值都是static,按照規則,其相對位置應該是相對于瀏覽器左上角。
<style type="text/css">
html{
margin: 20px;
border: solid 1px red;
position: static;
}
body{
border: solid 1px blue;
position: static;
padding: 20px;
}
.parent{
margin: 10px 0px;
width: 400px;
height: 300px;
background-color: pink;
color: white;
position: static;
}
.child{
width: 200px;
height: 60px;
background-color: #5bc0de;
color: white;
position: absolute;
box-sizing: border-box;
padding: 20px;
left: 0px;
top: 0px;
box-shadow: 0px 8px 16px rgba(0,0,0,0.18);
}
</style>
<body>
<div class="parent">
parent div
<div class="child">
absolute div
</div>
</div>
</body>
效果圖(紅色框代表html區域,藍色框代表body區域):
如果body屬性設置position:relative,會出現什么結果呢?
所以,你肯定也就知道了,下面這種效果怎么實現了吧
上述效果代碼:
.parent{
margin: 10px 0px;
width: 400px;
height: 300px;
background-color: pink;
color: white;
position: relative; /*設置父元素的postion值為非static*/
}
.child{
width: 200px;
height: 60px;
background-color: #5bc0de;
color: white;
position: absolute;
box-sizing: border-box;
padding: 20px;
left: 400px; /*設置偏移距離*/
top: 0px;
box-shadow: 0px 8px 16px rgba(0,0,0,0.18);
}
4.fixed
fixed很簡單,脫離文檔流,相對瀏覽器窗口定位,即使頁面內容滾動,fixed區域位置不會跟著變動。z-index確定層疊關系。
參考博客:CSS中position屬性( absolute | relative | static | fixed )詳解