關(guān)于CSS position,來自MDN的描述:
CSS position屬性用于指定一個元素在文檔中的定位方式。top、right、bottom、left 屬性則決定了該元素的最終位置。
先看一個圖片:

代碼如下:
<body>
<div class="parent1">
<div class="child1-1">child1-1</div>
<div class="child1-2">child1-2</div>
<div class="child1-3">child1-3</div>
<div class="child1-4">child1-4</div>
</div>
</body>
<style type="text/css">
.parent1{
background-color: chocolate;
width: 300px;
height: 300px;
margin: 25px 50px 75px;
}
.child1-1{
background-color: cornflowerblue;
width: 60px;
height: 60px;
}
.child1-2{
background-color:crimson;
width: 60px;
height: 60px;
}
.child1-3{
background-color:darkcyan;
width: 60px;
height: 60px;
}
.child1-4{
background-color: darkgreen;
width: 60px;
height: 60px;
}
</style>
這里展示的就是一個正?!拔臋n流”,
Normal flow
Boxes in the normal flow belong to a formatting context, which may be block or inline, but not both simultaneously. Block-level boxes participate in a block formatting context. Inline-level boxes participate in an inline formatting context.
個人理解:顧名思義就是像寫文檔一樣,一行一行的排列,如圖,每個child 都是一個60*60 的小方塊,即使在他們右邊有多余的位置,但是它們還是占一行。position就是每個元素的定位屬性,而默認就是 position = static,即上圖中parent 和 child 都是展示的文檔流樣式。
而position屬性一共有以下取值:
static
默認值。沒有定位,元素出現(xiàn)在正常的流中(忽略 top, bottom, left, right 或者 z-index 聲明)-
relative
生成相對定位的元素,相對于其正常位置進行定位。 如我們將上面的代碼改成// ... .child1-2{ background-color:crimson; width: 60px; height: 60px; position: relative; left: 20px; top: 30px; }relative
可以看到 child1-2 在原來的位置上,左邊多出了 20px ,距離頂部多出了 30px
-
absolute
生成絕對定位的元素,相對于 static 定位以外的第一個父元素進行定位。
我們將上例的child1-2恢復(fù),然后操作child1-3.child1-3{ background-color:darkcyan; width: 60px; height: 60px; position: absolute; left: 20px; top: 30px; }absolute
可以看到,child1-3 的位置已經(jīng)和 parent 無關(guān)了(因為 parent 的 position = "static"),很多時候,都會將 parent 設(shè)置成relative 來和 absolute child 配合使用。
我們再改一下 child1-3 的代碼.child1-3{ background-color:darkcyan; width: 60px; height: 60px; position: absolute; left: 20px; bottom: 30px; // 注意這個 }bottom 30px
bottom 30px 增加瀏覽器的高度
可以看到,child1-3 其實是一直跟著瀏覽器的高度在變化的。
-
fixed
.child1-4{ background-color: darkgreen; width: 60px; height: 60px; position: fixed; bottom: 30px; left: 70px; }fixed
而且,當瀏覽器高度變化時,他們兩個也會跟著變化。
但是,兩者的區(qū)別就在于,當 parent 設(shè)置成 position = relative 時,.parent1{ background-color: chocolate; width: 300px; height: 300px; margin: 25px 50px 75px; position: relative; }parent position = relative
即此時,child1-3 的 left,right 等以 parent 為基準。
inherit
規(guī)定應(yīng)該從父元素繼承 position 屬性的值。
這個就不需要圖解了。。。。





