一 咱們先來看下W3C上的定義:
1 position 屬性把元素放置到一個靜態的、相對的、絕對的、或固定的位置中。注意:static和relative仍然佔據標準流的位置。
static 默認。位置設置爲 static 的元素,它始終會處於頁面流給予的位置(static 元素會忽略任何 top、bottom、left 或 right 聲明)。
relative 位置被設置爲 relative 的元素,可將其移至相對於其正常位置的地方,因此 “left:20” 會將元素移至元素正常位置左邊 20 個像素的位置。
absolute 位置設置爲 absolute 的元素,可定位於相對於包含它的元素的指定座標。此元素的位置可通過 “left”、”top”、”right” 以及 “bottom” 屬性來規定。
fixed 位置被設置爲 fixed 的元素,可定位於相對於瀏覽器窗口的指定座標。此元素的位置可通過 “left”、”top”、”right” 以及”bottom” 屬性來規定。不論窗口滾動與否,元素都會留在那個位置。工作於 IE7(strict 模式)。
二 重點來看absolute :
1 當父元素設置了除static定位之外的定位的時候,(也就是說父元素可以是absolute relative ),子元素相對於父元素定位,可是相對於父元素哪裏定位呢?這個時候,基準是父元素的內容區(也即是content(width+height)+padding區域,不包括border和margin。
2 當父元素沒有設置定位的時候,子元素相對於body進行定位。
3 子元素定位的邊界是包括子元素的 整體 = margin + border + padding + content ;的margin外邊界爲基準進行定位。
三 代碼解析:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>position</title>
<style type="text/css">
.one{
width: 980px;
height: 300px;
margin: 0 auto;
background-color: pink;
}
.two {
height: 200px;
width: 400px;
float: left;
background-color: blue;
/*padding-left: 100px;*/
margin-left: 100px;
position: relative;
border: 30px solid green;
}
.three{
position: absolute;
width: 15px;
height: 15px;background-color: red;
/*left: 0;
left: 20px;
left: -20px;
bottom: 10px;*/
}
</style>
</head>
<body>
<div class="one">
<div class="two">
<div class="three"> </div>
</div>
</div>
</body>
</html>
該案例重點理解子元素定位的基準,當父元素設置了除static定位之外的定位的時候,子元素相對於父元素定位,可是相對於父元素哪裏定位呢?這個時候,基準是父元素的內容區(width+height)+padding,不包括border和margin
四 瀏覽器窗口顯示
座標以content+padding左上角偉基準
紅色的盒子 three 是absolute定位,其基準是藍色的盒子 two 的content和padding區 ,並不包括 border(綠色部分)。