天天看點

CSS中,relative和absolute的差別,及結合使用

固定定位

寫法:position:fixed;

不會随浏覽器視窗的滾動條滾動而變化,總是在視線裡的元素(例如兩邊的廣告,這個比較簡單就不進行介紹)

相對定位

寫法:position:relative;

定位為relative的元素脫離正常的文檔流中,但其在文檔流中的原位置依然存在。

相對于本身偏移,沒有脫離文檔流。

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

效果:

CSS中,relative和absolute的差別,及結合使用

可以看到它左偏移是相對于box-item1,而上偏移則是相對于父級box。是以說,它是相對于自身的位置偏移。

絕對定位

寫法:position:absolute;

定位為absolute的層脫離正常文檔流,但與relative的差別:其在正常流的中的原位置不再存在

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

效果:(設定TRBL,沒有給top,right,bottom,left值)

CSS中,relative和absolute的差別,及結合使用
<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>
      

效果:

CSS中,relative和absolute的差別,及結合使用

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或relative的父層,而這個父層并不一定時其直接父層
  • 對于​

    ​absolute定位​

    ​的層,如果其父層中都未定義absolute或relative,則其将相對body(浏覽器)進行定位