HTML/CSS属性position值static、fixed、relative和absolute的区别与用法

1、static:静态定位,默认,相当于没设置,top、right、bottom、left属性(以下简称TRBL)和z-index属性不生效

2、fixed:固定定位,相对于浏览器窗口来定位,TRBL属性和z-index属性有效

3、relative:相对定位,相对于直接父级来定位,TRBL属性和z-index属性有效

4、absolute:绝对定位,相对于同类父级来定位,即向上查找紧邻的父级position属性为fixed/relative/absolute的元素来定位,TRBL属性和z-index属性有效

 

示意图:

 

HTML代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>position</title>

</head>
<style>
    .div {
        width: 300px;
        height: 300px;
        background-color: gray;
    }

    .middle {
        width: 230px;
        height: 120px;
        margin: 10px;
        background-color: lightblue;
        border: 1px solid white;
    }

    .static {
        width: 90px;
        height: 90px;
        top: 20px;
        right: 0px;
        bottom: 0px;
        left: 30px;
        background-color: yellow;
        border: 1px solid white;
        position: static
    }

    .relative {
        width: 200px;
        height: 120px;
        top: 20px;
        right: 0px;
        bottom: 0px;
        left: 30px;
        background-color: green;
        border: 1px solid white;
        position: relative
    }

    .absolute {
        width: 180px;
        height: 110px;
        top: 20px;
        right: 0px;
        bottom: 0px;
        left: 30px;
        background-color: coral;
        border: 1px solid white;
        position: absolute
    }

    .fixed {
        width: 160px;
        height: 100px;
        top: 230px;
        right: 0px;
        bottom: 0px;
        left: 330px;
        background-color: blue;
        border: 1px solid white;
        position: fixed
    }
</style>

<body>

<div class="div">
    <div class="static">
        div1/static
    </div>
</div>

<br>

<div class="div">
    <div class="relative">
        div2/relative
        <div class="middle">
            middle
            <div class="absolute">
                middle/absolute
            </div>
        </div>
    </div>
</div>

<br>

<div class="div">
    <div class="absolute">
        div3/absolute
        <div class="absolute">
            absolute/absolute
        </div>
    </div>
</div>

<br>

<div class="div">
    <div class="fixed">
        div4/fixed
        <div class="absolute">
            fixed/absolute
        </div>
    </div>
</div>

</body>
</html>

 

参考资料

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值