position属性共有四种不同的定位方法,分别是static、fixed、relative、absolute。
position:static
static定位是HTML元素的默认值,即没有定位,元素出现在正常的流中。因此这种定位就不会受到top、bottom、left、right的影响。
<div class="wrap">
<div class="content"></div>
</div>
.wrap{height: 200px;width: 200px;background-color: #ddd;}
.content{height: 80px;width: 80px;background-color: rgb(228,183,41);position: static;top: 20px;left: 20px;}
position:fixed
fixed定位是指元素的位置相对于浏览器窗口是固定位置,即使窗口是滚动的他也不会滚动,而且fixed定位使元素的位置与文档流无关,因此不占据空间,所以会和其他元素发生重叠。
<div class="wrap">
<div class="content"></div>
</div>
.wrap{height: 1200px;background-color: #ddd;}
.content{height: 200px;width: 200px;background-color: rgb(228,183,41);position: fixed;bottom: 0px;right: 0px;}
fixed定位在IE7和IE8下需要描述!DOCTYPE才能支持
position:relative
相对定位元素的定位是相对他自己的正常位置定位。
<h2>正常的标题位置。</h2>
<h2 class="pos_bottom">position:relative的标题位置。</h2>
<h2 class="pos_left">position:relative的标题位置。</h2>
.pos_bottom{position: relative;bottom: -15px;}
.pos_left{position: relative;left: 30px;}
即可以理解为:移动后是移动前的负的位置。
即:移动后相对于移动前:如果值为负数,则直接转换成为整数;如果值是整数,则直接改变方向。
position:absolute
绝对定位的元素相对于最近的已定位父元素,如果元素没有已定位的父元素,那么它的位置相对于<html>。
<div class="wrap">
<div class="content">
<span>我在这里</span>
</div>
</div>
.wrap{height: 400px;width: 400px;background-color: #ddd;}
.content{height: 200px;width: 200px;background-color: rgb(228,183,41);}
span{position: absolute;right: 80px;background-color: red;}
只在span中设置position:absolute,效果如下:
在.content中设置position:absolute/fixed/relative,效果如下:
在.wrap中设置position:absolute/fixed/relative,效果如下:
因此,当某个absolute定位元素的父元素具有position:absolute/fixed/relative时,定位元素都会根据父元素来定位,而父元素没有position属性或者设置了默认属性,那么定位属性会依据html元素来定位。