position可能的值:
值 | 描述 |
---|---|
absolute | 生成绝对定位的元素,相对于 static 定位以外的第一个父元素进行定位。 元素的位置通过 "left", "top", "right" 以及 "bottom" 属性进行规定。 |
fixed | 生成绝对定位的元素,相对于浏览器窗口进行定位。 元素的位置通过 "left", "top", "right" 以及 "bottom" 属性进行规定。 |
relative | 生成相对定位的元素,相对于其正常位置进行定位。 因此,"left:20" 会向元素的 LEFT 位置添加 20 像素。 |
static | 默认值。没有定位,元素出现在正常的流中(忽略 top, bottom, left, right 或者 z-index 声明)。 |
inherit | 规定应该从父元素继承 position 属性的值。 |
所以当把一个元素的position定义为absolute的时候,根据它的父元素的position值,会产生不同的位置结果:
1.
<div id="father" style="margin:auto ; margin-top:30px; width:300px ; height:100px ; border:1px solid #999">
<div id="son" style="position:absolute; top:5px ; right:5px ; width:110px ; height:40px ; background:url('./img/button.png'); ">
</div>
</div>
因为它老子的position值为默认值(static,无定位),所以就是下面这个结果,儿子离他爹十万八千里。
2.
现在想办法让儿子回到他爹身边,于是:
<div id="father" style="position:absolute ; top:30px ; left:200px ; width:300px ; height:100px ; border:1px solid #999">
<div id="son" style="position:absolute ; top:5px ; right:5px ; width:110px ; height:40px ; background:url('./img/button.png'); ">
</div>
</div>
现在爹也变成了absolute,顿时爷俩消除了代沟,乖乖回到他爹身边,以后他爹跑到天涯海角也不离他爹一步了。