天天看点

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(浏览器)进行定位