Css元素布局定位

时间:2020-11-29 06:06:24
<!DOCTYPE HTML>
<html lang="zh-cn">
<head>
<meta charset="UTF-8">
<title>CSS POSITION</title>
<style type="text/css">
.wrap{position:relative;height:800px;z-index:1;}
.ps, .pf, .pr, .pa{width:80px;height:80px;line-height:80px;text-align:center;color:#FFF;font-weight:600;font-size:18px;}
.ps{position:static;background-color:silver;}
.pf{position:fixed;background-color:green;top:50%;left:50%;}
.pr{position:relative;background-color:red;top:30px;right:-130px;z-index:10;}
.pa{position:absolute;background-color:orange;top:60px;left:60px;}
</style> </head>
<body>
<div class="wrap">
<div class="ps">static</div>
<div class="pf">fixed</div>
<div class="pr">relative</div>
<div class="pa">absolute</div>
</div>
</body>
</html>

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

relative:相对于其正常位置进行定位。因此,"left:20" 会向元素的 LEFT 位置添加 20 像素。

fixed:相对于浏览器窗口进行定位。元素的位置通过 "left", "top", "right" 以及 "bottom" 属性进行规定。

absolute:生成绝对定位的元素,相对于 static 定位以外的第一个父元素进行定位。元素的位置通过 "left", "top", "right" 以及 "bottom" 属性进行规定。

CSS position:
static:默认属性,静态定位
relative:相对定位,相对于父元素的定位,需要配合top,left,right,bottom,z-index等属性
absolute:绝对定位,相对于父元素的定位,需要配合top,left,right,bottom,z-index等属性
fixed:固定定位,相对于父元素的定位,需要配合top,left,right,bottom,z-index等属性(IE6不支持)
通过修改.wrap{position:absolute;top:80px;height:800pxz-index:1;} 修改父元素的位置,看到static、relative、absolute 是相对父亲元素位置的改变而发生偏移