position属性是指本体对上级的定位。有四个:static、absolute、relative、fixed
先放测试代码:
<span style="font-size:14px;"><!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>position-absolute</title>
</head>
<body>
<div class="topline"></div>
<div class="father">
<div class="son1"></div>
<div class="son2"></div>
</div>
<div class="bottomline"></div>
</body>
</html></span>
样式为
.father{ background: red; width:50%; height:200px; } .son1{ background: blue; width:80%; height:50%; } .son2{ background: pink; width:80%; height:50%; } .topline{ width:100%; height:50px; background: green; } .bottomline{ width:100%; height:50px; background: yellow; }
1、static
position的默认属性,一般不设置position属性时,会按照正常的文档流进行排列。
对于测试代码,就是father和son都没有设置position属性,结果如下:
2.absolute
(1)如果son1不存在一个有着position属性的父对象,那么那就会以body为定位对象,按照浏览器的窗口进行定位。
son1设置absolute
son1完全按照body来定位,甚至是其宽高。
为了分辨son2的位置,把son1宽度缩小为10%
son2直接忽略了son1,从father开始定位。
(2)当son1的父对象(或曾祖父,只要是父级对象)father也设置了position属性,且position的属性值为absolute或者relative时,也就是说,不是默认值的情况,此时son1按照这个father来进行定位。
son1、father设置absolute,为了显示出son2,son1宽度为10%,注意,此时其宽度的10%是father宽度的10%
注意,定位点问题,如果parent设定了margin,border,padding等属性,那么这个定位点将忽略padding,将会从padding开始的地方(即只从padding的左上角开始)进行定位,也就是忽略padding,当然并不会忽略margin和border。
3.relative
但当设置son1为的position为relative后,将根据top,right,bottom,left的值按照它理应所在的位置进行偏移。所以,relative是要和trbl结合使用的。
son1设置为relative,并且top设置50px
son2不受影响
注意:relative的偏移是基于对象的margin的左上侧的。
4.fixed
fixed是特殊的absolute,即fixed总是以body为定位对象的,按照浏览器的窗口进行定位,即使拖动滚动条,他的位置也是不会改变的。与background-attachment:fixed相似,当然在Dreamweaver下似乎没有支持
son1设置为fixed,把bottomline长度设置为1000px,拖动后son1位置不变