position 屬性
position 屬性指定了元素的定位類型。
position 屬性的五個值:
static:默認值
relative:相對定位
fixed:固定位置
absolute:絕對定位
sticky:粘性定位
HTML實例
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>position</title>
<style type="text/css">
*{margin:0;padding:0;}
.clearfix:before,.clearfix:after {content:"";display:table;}
.clearfix:after {clear:both;overflow:hidden;}
.clearfix {zoom:1;}
.mgt20{margin-top:20px;}
.w1000{width:1000px;margin:0 auto;min-height:1900px;}
#demo{
position:relative;
border:1px solid #000;
margin-top:50px;
top:-50px;
line-height:18px;
}
.static,.fixed,.absolute,.relative{
width:200px;
}
.relative{
position:relative;
left:150px;
top:-20px;
background-color:#ffe4e1;
}
.static{
position:static;
background-color:#bbb;
}
.fixed{
position:fixed;
top:200px;
left:50%;
margin-left:-500px;
background-color:#ffc0cb;
}
.absolute{
position:absolute;
right:10px;
top:10px;
background-color:#b0c4de;
}
</style>
</head>
<body>
<div class="w1000">
<div class="mgt20 clearfix">
<div id="demo" class="clearfix">
<div class="static">static: 默認值。無特殊定位,對象遵循HTML定位規則 </div>
<div class="absolute">absolute: 將對象從文檔流中拖出,使用left,right,top,bottom 等屬性相對於其最接近的一個最有定位設置的父對象進行絕對定位。如果不存在這樣的父對象,則依據body對象。而其層疊通過z-index屬性定義 </div>
<div class="fixed">fixed屬性的說明:fixed總是以body爲定位時的對象,總是根據瀏覽器的窗口來進行元素的定位,通過"left"、 "top"、 "right"、"bottom" 屬性進行定位。</div>
<div class="relative">relative1:對象不可層疊,對象原來佔有的位置保留,但將依據 left,right,top,bottom 等屬性在正常文檔流中偏移位置 </div>
</div>
</div>
</div>
</body>
</html>
absolute絕對定位
生成絕對定位的元素,相對於 static 定位以外的第一個父元素進行定位。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>定位頁面</title>
</head>
<style>
div.pos_QM{
position:absolute;
left:100px;
top:150px;
width:200px;
height:200px;
background-color:black;
color:white;
text-align:center;
}
div{
border:2px solid black;
}
</style>
<body>
<div class="pos_QM">
這是一個絕對定位的盒子
</div>
<div>
通過絕對定位,元素可以放置在頁面上的任何位置,下面的黑色盒子距離頁面左側100px,距離頁面頂部150px.
</div>
</body>
</html>
取值
static
該關鍵字指定元素使用正常的佈局行爲,即元素在文檔常規流中當前的佈局位置。此時 top, right, bottom, left 和 z-index 屬性無效。
relative
該關鍵字下,元素先放置在未添加定位時的位置,再在不改變頁面佈局的前提下調整元素位置(因此會在此元素未添加定位時所在位置留下空白)。position:relative 對 table-*-group, table-row, table-column, table-cell, table-caption 元素無效。
absolute
不爲元素預留空間,通過指定元素相對於最近的非 static 定位祖先元素的偏移,來確定元素位置。絕對定位的元素可以設置外邊距(margins),且不會與其他邊距合併。
fixed
不爲元素預留空間,而是通過指定元素相對於屏幕視口(viewport)的位置來指定元素位置。元素的位置在屏幕滾動時不會改變。打印時,元素會出現在的每頁的固定位置。fixed 屬性會創建新的層疊上下文。當元素祖先的 transform 屬性非 none 時,容器由視口改爲該祖先。
sticky
盒位置根據正常流計算(這稱爲正常流動中的位置),然後相對於該元素在流中的 flow root(BFC)和 containing block(最近的塊級祖先元素)定位。在所有情況下(即便被定位元素爲 table 時),該元素定位均不對後續元素造成影響。當元素 B 被粘性定位時,後續元素的位置仍按照 B 未定位時的位置來確定。position: sticky 對 table 元素的效果與 position: relative 相同。
常見語法
static | relative | absolute | sticky | fixed