css Position用法

发布时间 2023-04-08 19:31:33作者: 沈先生爱猫咪

相对位置和绝对位置

现有3个div如下

 <style>
        .brother {
            width: 200px;
            height: 200px;
            background-color: yellow;

        }

        .father {
            width: 200px;
            height: 200px;
            background-color: green;

        }

        .son {
            width: 50px;
            height: 50px;
            background-color: blue;
        }
    </style>
    <div class="brother"></div>
    <div class="father">
        <div class="son"></div>
    </div>

需求是把蓝色的div放在绿色div的右边
实现效果如下

具体实现代码:

 <style>
        .brother {
            width: 200px;
            height: 200px;
            background-color: yellow;

        }

        .father {
            width: 200px;
            height: 200px;
            background-color: green;
            position: relative;
        }

        .son {
            width: 50px;
            height: 50px;
            position: absolute;
            right: 0;
            background-color: blue;
        }
    </style>
    <div class="brother"></div>
    <div class="father">
        <div class="son"></div>
    </div>

当一个元素设置为绝对定位 absolute时,会去找其标记了 position:relative的祖先作为参考系,以它为基准进行left right bottom 的偏移,若没找到,则以body标签作为参考系,即视口 x,y 坐标都为0的点

固定定位

标记了 position: fixed;的元素将脱离文档流,固定在视口(0,0)这个位置,以视口(0,0)这个坐标作为参考系

 <style>
        .fix {
            width: 100px;
            height: 100px;
            background-color: blue;
            /* 脱离文档流 */
            position: fixed;
            right: 0;
            bottom: 50%;
        }
    </style>