相对定位vs绝对定位

<!-- -->
相对定位,
position: relative;

它会,相对它原来的位置的坐标的左上角,进行偏移。
同时,它原来的位置会被保留

(相对定位的html容器,它虽然已经脱离了普通的文档流,
但它依然被视为普通文档流定位的一部分。)

口语化的描述,“我人不在这,但位置你得给我留着”。


<!-- -->

绝对定位,
position:absolute;

它会,相对于整个文档的左上角原点的坐标,进行偏移。
同时,它原来的位置,不会被保留。

(就是被添加了绝对定位的html标签,
它会完全的脱离整个文档流
不再在页面上占有空间。)

<!-- -->

相对定位和绝对定位的区别:
1,定位坐标不同;
2,相对定位原位置保留;绝对定位不保留。

<!-- -->
当二个绝对定位的容器,发生重叠的时候,
如何决定重叠的顺序?

1、html代码中,哪个容器后被加载,哪个容器就处于“重叠的上面一层”。?先加载标准流?
2、z-index,用来设置“定位容器”的堆叠顺序,它的值没有单位。

z-index,理论上可以无限的往上加,
但事实上它受计算机数值极限的限制。

《》

 一个绝对定位的容器,它的父容器是相对定位的时候,
 这个绝对定位的容器,将以它的相对定位的父容器的左上角为原点,进行定位。
<!-- 相对定位和绝对定位 -->

<style type="text/css">
.sty1{
        width:200px;height: 50px;background: #666;
        margin:10px;color: #fff;font-size: 33px;
    }

.sty222{
        width:200px;height: 50px;background: #999;
        margin:10px;color: #fff;font-size: 33px;
        /*原来的位置在现在的左边20px,上方20px处,*/
        position: relative;
        left: 20px;top: 20px;
    }

.sty333{
        width:200px;height: 50px;background: #999;
        margin:10px;color: #fff;font-size: 33px;
        /*绝对定位是相对于页面的左上角的原点*/
        position:absolute;
        left: 120px;top: 20px;
        z-index: 1;
        /*z-index越大,越先显示谁。*/
    }

.sty444{
        width:200px;height: 50px;background: #0F0;
        margin:10px;color: #fff;font-size: 33px;

        position:absolute;
        left: 130px;top: 30px;z-index: 13;
    }
</style>

<div class="sty1">11111</div>
<div class="sty222">22222</div>
<div class="sty1">11111</div>
<!-- 相对定位原来的位置保留 -->

<div class="sty444">444444</div>
<div class="sty333">3333333</div>
<div class="sty1">11111</div>
<!-- 绝对定位原来的位置不保留 -->

<meta charset='utf-8' />
<style type="text/css">
    .wrap{
        width:80%;height: 200px;background: #666;
        margin:10px auto;
        position: relative;
    }
    .sty2{
        width:80px;height: 150px;background: #999;margin:10px;
        position: absolute;
        left: -103px;
        top: 10px;
    }
    .sty3{
        width:80px;height: 70px;background: #999;margin:10px;
        position: absolute;
        /*left: 90%;*/
        right:-103px;
        bottom: 10px;
    }
</style>

<div class="wrap">
    <div class="sty2">左边</div>
    <div class="sty3">右边</div>
</div>
<!-- 使用绝对定位和相对定位,来做左右二侧的广告位 -->
<!-- 
    当,
    一个绝对定位的容器,它的父容器是相对定位的时候,
    这个绝对定位的容器,将以它的相对定位的父容器的左上角为原点,
    进行定位。
 -->

原文地址:https://www.cnblogs.com/lovely7/p/7580720.html