绝对定位和相对定位

相对定位

元素设置position值:position:relative;  此属性值的设置,元素没有脱离文档流,还是普通流定位模型的一部分,会对文档流中其它元素布局产生影响

首先给大家演示一个代码

<!DOCTYPE html>
<html>
<head>
<style>
.div1{background-color:red;height:100px}
.div2{background-color:green;height:50px;}
.div3{background-color:blue;height:30px}
</style>
</head>
<body>
<div class="div1"></div>
<div class="div2"></div>
<div class="div3"></div>
</body>
</html>

页面显示结果:

接着我们将第二个div加入relative相对定位属性,他会保留原有位置,根据原有文档位置进行相对定位:

 1 <!DOCTYPE html>
 2 <html>
 3 <head>
 4 <style>
 5 .div1{background-color:red;height:100px}
 6 .div2{background-color:green;height:50px;position:relative;top:90px}
 7 .div3{background-color:blue;height:30px}
 8 </style>
 9 </head>
10 <body>
11 <div class="div1"></div>
12 <div class="div2"></div>
13 <div class="div3"></div>
14 </body>
15 </html>

需要注意的是相对定位并没有脱离文档流


 

绝对定位

设置position值:position:absolute; 此属性值的设置,元素从文档流完全删除

绝对定位的元素的偏移位置以最近的定位(包括相对定位和绝对定位)祖先元素作参照物。如果元素没有已定位(包括相对定位和绝对定位)的祖先元素,那么它的参照物为最顶级元素(由于浏览器的默认参照物不同,物可能是BODY或 HTML 元素)。

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <style>
        .div1{background-color:red;height:100px;}
        .div{background-color:yellow;height:50px;}
        .div2{background-color:green;height:20px;}
        .div3{background-color:blue;height:30px}
    </style>
</head>
<body>
<div class="div1"></div>
<div class="div">
    <div class="div2">
     这是绝对定位元素
    </div>
</div>
<div class="div3"></div>
</body>
</html>

显示如下:

之后为div2设置absolute,如果

.div2{background-color:green;height:20px;position: absolute;}
如果没有指定绝对定位位置,则还是保留在原来的文档流中初始位置,若果指定位置后,就会销毁文档流中的位置。
 1 <!DOCTYPE html>
 2 <html>
 3 <head>
 4     <meta charset="UTF-8">
 5     <style>
 6         .div1{background-color:red;height:100px;}
 7         .div{background-color:yellow;height:50px;position: relative;top:20px}
 8         .div2{background-color:green;height:20px;position: absolute;top:10px}
 9         .div3{background-color:blue;height:30px}
10     </style>
11 </head>
12 <body>
13 <div class="div1">1</div>
14 <div class="div">
15     2
16     <div class="div2">
17      这是绝对定位元素
18     </div>
19 </div>
20 <div class="div3">3</div>
21 </body>
22 </html>

 



posted on 2015-07-08 11:23  句号小弟wutian  阅读(135)  评论(0编辑  收藏  举报