绝对定位和相对定位

相对定位html

元素设置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>

页面显示结果:spa

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

 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>

须要注意的是相对定位并无脱离文档流htm


 

绝对定位blog

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

绝对定位的元素的偏移位置以最近的定位(包括相对定位和绝对定位)祖先元素做参照物。若是元素没有已定位(包括相对定位和绝对定位)的祖先元素,那么它的参照物为最顶级元素(因为浏览器的默认参照物不一样,物多是BODY或 HTML 元素)。it

<!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>

显示以下:io

以后为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>

 

相关文章
相关标签/搜索