position 的值(定位)

133 阅读1分钟

静态定位:static

static 为默认值,静态定位不脱标,top , right ,bottom , left 等属性不生效

绝对定位:absolute

绝对定位会脱标,参照物采用就近原则,找最近一级带有定位的父级元素进行位置移动,如果都没有,就找浏览器窗口

相对定位:relative

相对定位不脱标,参照物是自身偏移前的位置

固定定位:fixed

固定定位会脱标,参照物是浏览器窗口

子绝父相经典应用场景:实现盒子水平垂直居中

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .father{
            position: relative;
            width: 200px;
            height: 200px;
            background-color: #ccc;
        }
        .son {
            position: absolute;
            width: 100px;
            height: 100px;
            left: 0;
            right: 0;
            top: 0;
            bottom: 0;
            margin: auto;
            background-color: pink;
        }
    </style>

</head>

<body>
    <div class="father">
        <div class="son"></div>
    </div>
   </script>
</body>

</html>

image.png