css基礎知識中,定位是最重要的一項。現在整理一下定位的相關知識,留作以後複習用。
css定位機制有三種:普通流、浮動和定位。
普通流:普通流中元素框的位置由元素在HTML文檔中的位置決定。塊級元素從上到下依次排列,塊級元素的垂直距離由垂直方向的margin計算得到。行內元素在一行之中水平放置。
浮動:浮動框可以左右移動,直到它的外邊框接觸到包含框邊緣或其他浮動框邊緣。浮動框脫離普通流。
定位:position定位
Position屬性
position屬性可以選擇5個不同類型的定位屬性:static、relative、absolute、fixed、inherit。
static
position屬性的默認值,元素正常出現在文檔流中。
HTML
<div class="box-set";
<div class="box">box1</div>
<div class="box">box2</div>
<div class="box">box3</div>
<div class="box">box4</div>
</div>
CSS
.box-set{
background-color:#eaeaea;
}
.box{
background-color:red;
width:48px;
height:48px;
}
效果
relative
生成相對定位元素,通過使用位移屬性(top、right、bottom、left)相對於正常位置進行定位。
設置了位移屬性的相對定位元素,在頁面中仍然屬於自然流,其他元素不會佔用相對元素原本在文檔流中的位置,相對元素可能會於其他元素重疊。
位移屬性若同時設置了“top”和“bottom”,“top”優先級較高。
HTML
<div class="box-set">
<div class="box box-1">box1</div>
<div class="box box-2">box2</div>
<div class="box box-3">box3</div>
<div class="box box-4">box4</div>
</div>
CSS
.box-set{
background-color:#eaeaea;
}
.box{
background-color:red;
width:48px;
height:48px;
position:relative;
}
.box-1{
top:10px;
}
.box-2{
left:20px;
}
.box-3{
bottom:-10px;
right:10px;
}
效果
absolute
絕對定位元素相對於已定位的(除static定位)最近的祖先元素進行定位,如果沒有最近的祖先元素,則相對於頁面主體進行定位。
絕對定位元素會脫離文檔流,有可能會覆蓋其他元素,可以設置z-index屬性來設置元素堆疊順序。
HTML
<div class="box-set">
<div class="box box-1">box1</div>
<div class="box box-2">box2</div>
<div class="box box-3">box3</div>
<div class="box box-4">box4</div>
</div>
CSS
.box-set{
background-color:#eaeaea;
position:relative;
}
.box{
background-color:red;
width:48px;
height:48px;
position:absolute;
}
.box-1{
top:5%;
left:3%;
}
.box-2{
top:0;
right:-10px;
}
.box-3{
bottom:-10px;
right:10px;
}
.box-4{
bottom:0;
}
效果
fixed
固定定位和絕對定位類似,只是固定定位元素是相對於瀏覽器進行定位的,不會隨滾動條滾動。
HTML
<div class="box-set">
<div class="box box-1">box1</div>
<div class="box box-2">box2</div>
<div class="box box-3">box3</div>
<div class="box box-4">box4</div>
</div>
CSS
.box-set{
background-color:#eaeaea;
}
.box{
background-color:red;
width:48px;
height:48px;
position:fixed;
}
.box-1{
top:5%;
left:3%;
}
.box-2{
top:0;
right:-10px;
}
.box-3{
bottom:-10px;
right:10px;
}
.box-4{
bottom:0;
}
效果
固定頁頭和頁腳
固定頁頭、頁腳或者頁面的一個側邊都是常見的用途,不會隨着滾動條滾動。
通過設置“left”和“right”兩個盒子位移,這使得“頁腳”跨越了頁面的整個寬度,而不需使用margin、border和padding來破壞盒模形就做了收縮自如。
HTML
<footer>Footer</footer>
CSS
footer{
background-color:chartreuse;
position:fixed;
bottom:0;
left:0;
right:0;
}
效果
z-index屬性
z-index屬性設置元素的堆疊順序,z-index屬性值越高越靠前。
z-index屬性與位移屬性相同,僅能在定位元素上奏效(“relatvie”、“absolute”或者“fixed”之一)。
HTML
<div class="box-set">
<div class="box box-1">box1</div>
<div class="box box-2">box2</div>
<div class="box box-3">box3</div>
<div class="box box-4">box4</div>
</div>
CSS
.box-set{
background-color:#eaeaea;
position:relative;
}
.box{
background-color:red;
width:48px;
height:48px;
position:absolute;
}
.box-1{
left:10px;
top:10px;
}
.box-2{
top:40px;
left:40px;
z-index:3;
}
.box-3{
left:80px;
top:10px;
z-index:2;
}
.box-4{
top:40px;
left:120px;
z-index:1;
}
效果
設置z-index之前
設置z-index之後