relative 和 absolute

一、單獨使用:css

relative:相對於自己偏移,沒有脫離文檔流。html

<div class="box">     
<div class="box-item">box-item1</div>     
<div class="box-item relative">box-item2</div>     
<div class="box-item">box-item3</div> </div>
body{  
margin: 0;     
padding: 0;     
background-color: #81d6d2; 
} 
.box{  
width: 600px;     
height: 200px;     
margin: 50px;     
background-color: #d6f5c3;     
font-size: 0;     
-webkit-text-size-adjust:none; 
}  
.box-item{  
font-size: 14px;     
background-color: darkorange;     
width: 100px;     
height:100px;     
text-align: center;     
line-height: 100px;     
display: inline-block; 
} 
.relative{  
position:relative;     
top:20px;     
left:20px;     
background-color: lightcoral; 
}

效果:web

能夠看到它左偏移是相對於box-item1,而上偏移則是相對於父級box。所以說,它是相對於自身的位置偏移。瀏覽器

absolute:相對於瀏覽器定位,脫離了文檔流,也就是不佔位置。在沒有設定TRBL值時是根據父級對象的座標做爲起始點,當設定TRBL值後則根據瀏覽器的左上角做爲起始點,例子以下:spa

(沒有設置TRBL,沒有給top、left、bottom、right值).net

<style>  body{  
margin: 0;         
padding: 0;         
background-color: #81d6d2;     
}  
.box{  
width: 200px;         
height: 200px;         
margin: 50px;         
background-color: #d6f5c3;     
}  
.box-item{  
position:absolute;         
background-color: darkorange;         
width: 100px;         
height:100px;         
text-align: center;         
line-height: 100px;     
} 
</style>
 
<div class="box">     
<div class="box-item">box-item</div> 
</div>

效果:htm


(設置TRBL,沒有給top、right、bottom、left值對象

<style>  
body{  
margin: 0;         
padding: 0;         
background-color: #81d6d2;     
}  
.box{  
width: 200px;         
height: 200px;         
margin: 50px;         
background-color: #d6f5c3;     
}  
.box-item{  
position:absolute;         
top:20px;         
left:20px;         
background-color: darkorange;         
width: 100px;         
height:100px;         
text-align: center;         
line-height: 100px;     
} 
</style>

效果:blog



二、結合使用文檔

relative和absolute結合使用時,能夠再也不參照瀏覽器定位,而參照父級元素定位,從而更加自由。

<style>  
body{  
margin: 0;         
padding: 0;         
background-color: #81d6d2;     
}  
.box{  
position:relative;         
width: 200px;         
height: 200px;         
margin: 50px;         
background-color: #d6f5c3;     
}  
.box-item{  
position:absolute;         
top:20px;         
left:20px;         
background-color: darkorange;         
width: 100px;         
height:100px;         
text-align: center;         
line-height: 100px;     
} 
</style>

效果:



總結:使用這個組合定位,可以實現相對父元素定位。單獨使用relative只能相對自己偏移,單獨使用absolute只能相對瀏覽器偏移,absolute受到父級元素是否有position影響。若是父級元素沒有position值,則參照瀏覽器偏移,若是有(relative、absolute、fixed都行),則以父級元素爲參照物偏移。

參考:

一、https://developer.mozilla.org/zh-CN/docs/Web/CSS/position#示例

二、https://www.imooc.com/qadetail/143797

三、https://blog.csdn.net/u012006632/article/details/50553140

四、http://www.jb51.net/css/68072.html

相關文章
相關標籤/搜索