position屬性有四個值,分別是靜態定位(static)、相對定位(relative)、絕對定位(absolute)、固定定位(fixed),默認position值是static。
- 使用默認定位值的static效果。
<DOCTYPE html />
<html>
<title>position定位</title>
<style type="text/css">
*{padding:0;margin:0;}
.one{background-color:#ff0066;color:#000000;font-weight:bold;height:50px;width:300px;}
.two{background-color:#ffcc99;color:#000000;font-weight:bold;height:50px;width:300px;}
.three{background-color:#ffff99;color:#000000;font-weight:bold;height:50px;width:300px;}
.four{background-color:#99ff33;color:#000000;font-weight:bold;height:50px;width:300px;}
.five{background-color:#cc99ff;;color:#000000;font-weight:bold;height:50px;width:300px;}
div{margin-left:20px;margin-top:20px;}
</style>
<body>
<div>
<p class="one">The page one.</p>
<p class="two">The page two.</p>
<p class="three">The page three.</p>
<p class="four">The page four.</p>
<p class="five">The page five.</p>
</div>
</body>
</html>
position默認值static,每個元素都處在正常標準流中。
網頁顯示如下:
2. 相對定位(relative)
所謂相對定位,是元素相對於它本來在標準流中的位置而言的,單設一個position爲relative是看不出來效果的,所以我設置了top值。.two{background-color:#ffcc99;color:#000000;font-weight:bold;height:50px;width:300px;position:relative;top:20px;}
網頁顯示如下:
由圖可見,relative是讓元素相對於原位置移動的,並且除了設置相對定位的元素位置變了外,其他的元素位置並沒有變,移動了的元素原來所佔的空間也不變。
絕對定位(absolute)
絕對定位和相對定位不一樣,絕對定位是把元素徹底從文檔流中脫離出來。把相對定位改爲絕對定位:.two{background-color:#ffcc99;color:#000000;font-weight:bold;height:50px;width:300px;position:absolute;left:150px;top:20px;}
網頁顯示如下:
由圖可以看到,第二個元素完全脫離了文檔流。細心的人肯定會發現,top值是20px(left的表現不明顯,不過和top同理),但是它好像是相對於瀏覽器的,但其實是定義了absolute的元素是相對於離它最近的定位設置爲position或者relative的祖先元素的,如果沒有設置了定位的祖先元素,則它就相對於body元素移動。這裏可以給div添加屬性,div{margin-left:20px;margin-top:20px;position:relative;}
網頁顯示如下:
這兒父div的position也可以設置爲absolute,設置之後,後面的絕對定位纔有父元素相對移動。固定定位(fixed)
固定定位和絕對定位一樣,是完全脫離文檔流的,不同的是,固定定位是相對於瀏覽器窗口,所以它不會隨着頁面而滾動。.two{background-color:#ffcc99;color:#000000;font-weight:bold;height:50px;width:300px;position:fixed;left:150px;top:20px;}
靜態定定位網頁顯示如下:
固定定位一般用於設置導航欄。
總結:只有將元素的position設定爲relative、absolute、或者fixed的時候,這個元素的top、bottom、right、left屬性纔會起作用。