2018-07-10
2018-07-10 本文已影响0人
老头子_d0ec
相对定位与绝对定位:
之前一直搞不明白html中positon:relative; 和 position:absolute;这两个属性。这里记录一下。
理论解释
相对定位:该元素相对于自己原有位置,偏移一定距离。相对的是自己。
绝对定位:该元素相对于其父元素,偏移一定距离。相对的是父元素,重点是这个父元素也需要是设置了position属性。从最近的父元素开始找,直到找到body位置为止。
1)相对定位
<div id="test">
<p class="p1">相对定位:相对于自己原来的位置,偏移一些距离</p>
<p class="p2">相对定位,相对的是自己</p>
</div>
对应的css样式:
#test{
height: 300px;
width: 300px;
background: gray;
}
/*p标签本身会有padding和margin值*/
p{
margin: 0px;
padding: 0px;
}
.p1{
height: 100px;
width: 100px;
background: blue;
}
.p2{
height: 80px;
width: 80px;
background: red;
}
运行后效果是:(这时没有设置position属性呢

然后,给p1设置相对定位
.p1{
height: 100px;
width: 100px;
background: blue;
/*设置相对定位*/
position: relative;
/*相对于左边偏移20px,相对于上边偏移20px*/
left: 20px;
top:20px;
}1
运行后效果如下:

ok了,相对定位就是这样啦,需要注意的是,p1虽然偏移了,但是同时它还占着它原来的位置。
2)绝对定位
再增加一個div
<body>
<div id="test">
<p class="p1">相对定位:相对于自己原来的位置,偏移一些距离</p>
<p class="p2">相对定位,相对的是自己</p>
</div>
<div id="test2">
<p class="p3">绝对定位:相对于自己父元素的位置,偏移一些距离</p>
<p class="p4">绝对定位,相对的是父元素</p>
</div>
</body>1
相应的样式
#test2{
height: 300px;
width: 300px;
background: pink;
}
.p3{
height: 100px;
width: 100px;
background: green;
/*設置绝对定位*/
position: absolute;
left: 30px;
top: 30px;
}
.p4{
height: 90px;
width: 90px;
background: gold;
}1
同時將p1的相对定位去掉。这时候效果如下:

然後給p3設置绝对定位:
.p3{
height: 100px;
width: 100px;
background: green;
/*設置绝对定位*/
position: absolute;
left: 30px;
top: 30px;
}
.p4{
height: 90px;
width: 90px;
background: gold;
}1
觉得效果是怎樣呢?因爲test2是p3的父元素,所以猜測效果是p3相对于test2,向左偏移30px,向下偏移30px。那麽究竟是不是這樣呢??运行后效果如下:

我擦,跟想的不一樣啊。。。
別急,这是因为:虽然test2是p3的父元素,但是test2沒有設置position屬性,所以p3就會繼續向上找,找test2的父元素,直至到body为止。所以就出現了如上效果。那麽,如果想p3相对于test2,向左偏移30px,向下偏移30px,只需給test2設置position屬性即可。
#test2{
height: 300px;
width: 300px;
background: pink;
position: relative;
}1
效果如下:
