一、相對定位(relative)
首先,說一個文檔流的概念,有時候也叫做文本流。“流”表示連續不斷的意思,比如“流媒體”,這里的文檔(文本)流指的是源程序里面的代碼,也就是html里面 的標簽。
測試代碼:
<html>
<head>
<title>position</title>
<style type=”text/css”>
#div1{
height:80px;
width:400px;
background:red;
}
#div2{
height:80px;
width:300px;
background:blue;
position:relative;
left:20px;
top:-20px;
}
#div3{
height:80px;
width:300px;
background:green;
}
</style>
</head>
<body>
<div id=”div1″>
</div>
<div id=”div2″></div>
<div id=”div3″></div>
</body>
</html>
當設了相對的偏移量之后,這個DIV原來所占據的位置(文檔流)不會被下面的DIV塊擠占,而是空在那里;當偏移后向下或者向右的內容會被隱藏,而 這一點區別于絕對定位,絕對定位會出現滾動條。但是向左或者向右的內容超出當前瀏覽器的視線,無論是相對還是覺得定位,超出的部分都會被隱藏。
二、絕對定位(absolute)
當一個DIV塊的位置被定義為絕對定位的時候,也就意味著它失去了文檔流的位置,后面的文檔流會緊跟著補上來接替它的位置。如果上下左右的絕對偏移量都是零,那么它將漂浮在原來的位置上。否則就會以瀏覽器的上下左右四邊為基準進行偏移。
測試代碼:
<html>
<head>
<title>position</title>
<style type=”text/css”>
#div1{
height:880px;
width:400px;
background:red;
}
#div2{
height:80px;
width:300px;
background:blue;
position:absolute;
left:-80px;
bottom:-50px;
}
#div3{
height:880px;
width:300px;
background:green;
}
</style>
</head>
<body>
<div id=”div1″>
</div>
<div id=”div2″>
</div>
<div id=”div3″>
</div>
</body>
</html>
三、固定定位(fixed)
固定定位和絕對定位有相似之處,IE6以上版本才支持這項屬性,以我的理解,固定定位總是以當前的頁面為基準進行偏移,和背景圖片固定,內容滾動的效果一樣。
測試代碼:
<html>
<head>
<title>fixed</title>
<style type=”text/css”>
#div1{
background:green;
width:100px;
text-align:center;
新聞熱點
疑難解答