深圳市博士通科技有限公司

DIV里CSS定位属性position详解

2016/8/27 8:57:21   阅读:1537    发布者:1537

CSS定位元素有3种方式 :普通流、相对位置、绝对位置。通过设置position属性来实现。

position属性取值的含义
inherit

继承父元素position 属性的值。

static

默认值。没有定位,元素出现在正常的流中(忽略 top, bottom, left, right 或者 z-index 声明)。

relative

生成相对定位的元素,相对于元素本身正常位置进行定位。因此,

"left:20" 会向元素的 LEFT 位置添加 20 像素。

absolute

生成绝对定位的元素,找到第一个非static的祖先元素进行定位。

元素的位置通过 "left", "top", "right" 以及 "bottom" 属性进行规定。

fixed

生成绝对定位的元素,相对于浏览器窗口进行定位。元素的位

置通过 "left", "top", "right" 以及 "bottom" 属性进行规定。

普通流定位是:static,默认定位  相对位置定位是:relative 相对于该

元素本身作为普通流的位置,占有文档流的原来位置

绝对位置定位有2种:absolute和fixed,一个是相对自己的第一个非st

atic祖先元素,一个是相对浏览器窗口,都不占有原来的文档流位置

例子1:static普通流定位,红色div的top属性失效
<
body> <div style="border: solid 1px #0e0; width: 200px;"> <div style="height: 100px; width:100px; background-color:red; top:20px;"></div> <div style="height:100px; width:100px; background-color:green; "></div> <div style="height:100px; width:100px; background-color:blue;"></div> </div> </body>
例子2:relative相对位置,绿色div相对static的位置向右和向下移动了20px,绿色div原来的文档位置还在。
<
body> <div style="border: solid 1px #0e0; width: 200px;"> <div style="height: 100px; width:100px; background-color:red; top:20px;"></div> <div style="height:100px; width:100px; background-color:green; position:relative; top:20px; left:20px;"></div> <div style="height:100px; width:100px; background-color:blue;"></div> </div> </body>                                                                                                               
例子3.1:absolute绝对位置(不占有原来的文档流位置),没有指定父元素div的position属性, 
则绿色div的父级div是static定位,所以不选这个div做参照,选window作为参照
<
body> <div style="border: solid 1px #0e0; width: 200px;"> <div style="height: 100px; width:100px; background-color:red; top:20px;"></div> <div style="height:100px; width:100px; background-color:green; position:absolute; top:20px; left:20px; "></div> <div style="height:100px; width:100px; background-color:blue;"></div> </div> </body>
例子3.2:absolute绝对位置,父级div的position是relative,不再是static,所以选父级div为参考。
<
body> <div style="border: solid 1px #0e0; width: 200px; position:relative;"> <div style="height: 100px; width:100px; background-color:red; top:20px;"></div> <div style="height:100px; width:100px; background-color:green; position:absolute; top:20px; left:20px; "></div> <div style="height:100px; width:100px; background-color:blue;"></div> </div> </body>
例子4:fixed绝对位置,相对于窗口window的,不占文档流位置。
<
body> <div style="border: solid 1px #0e0; width: 200px; position:relative;"> <div style="height: 100px; width:100px; background-color:red; top:20px;"></div> <div style="height:100px; width:100px; background-color:green; position:fixed; bottom:20px; left:20px; "></div> <div style="height:100px; width:100px; background-color:blue;"></div> </div> </body>