相对定位和绝对定位的区别

一、相对定位:以自身原本的位置为起点计算偏移量,与其他元素无关,不会影响其他元素

        写法格式:position: relative;

<style>
    *{
        margin: 0;
        padding: 0;
    }
    .parent{
        width: 500px;
        height: 300px;
        border: 1px solid red;
    }
    .box1{
        width: 100px;
        height: 100px;
        background-color: orange;
        /* 相对定位 */
        position: relative;
        top:320px;
        left:100px;
    }
    .box2{
        width: 150px;
        height: 150px;
        background-color: forestgreen;
    }
</style>
<body>
    <div class="parent">
        <div class="box1">box1</div>
        <div class="box2">box2</div>
    </div>
</body>

未使用相对定位时:

对box1使用相对定位后;

 

 二、绝对定位:相对于第一个非static定位的父级元素进行定位可以通过top、right、bottom、left 这四个属性来设置元素相对于父级元素位置的偏移量。如果没有满足条件的父级元素,则会相对于浏览器窗口来进行定位。使用绝对定位的元素会对其他元素造成影响。

        书写格式:position: absolute;

<style>
    *{
        margin: 0;
        padding: 0;
    }
    .parent{
        width: 500px;
        height: 300px;
        border: 1px solid red;
    }
    .box1{
        width: 100px;
        height: 100px;
        background-color: orange;
        /* 绝对定位 */
        position: absolute;
        top: 200px;
        left: 200px;
    }
    .box2{
        width: 150px;
        height: 150px;
        background-color: forestgreen;
    }
</style>
<body>
    <div class="parent">
        <div class="box1">box1</div>
        <div class="box2">box2</div>
    </div>
</body>

未使用绝对定位之前:

 

对box1使用绝对定位之后:

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值