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属性才会起作用。