7.3 水平垂直居中

56 阅读1分钟
<!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>
        .parent{
            width: 200px;
            height: 200px;
            background-color: blue;
            /* 1.1水平垂直居中 mragin 给父元素设置border属性 */
            /* border: 1px solid red; */
            /* 2.1通过padding挤压 */
            /* padding: 50px; */
            /* 2.2将当前盒模型设置为边框盒子 */
            /* box-sizing: border-box; */
            /* 3.1给父元素设置相对定位 */
            /* position: relative; */
            /* 4.1 给父元素设置相对定位 */
            position: relative;

        }
        .child{
            width: 100px;
            height: 100px;
            background-color: red;
            /* 1.2 给子元素设置margin为宽高的一半 */
            /* margin: 50px; */
            /* 3.2给子元素设置绝对定位 配合属性为0 margin:auto */
            /* position: absolute;
            top: 0;
            bottom: 0;
            left: 0;
            right: 0;
            margin: auto; */
            /* 4.2给子元素设置绝对定位 top left 50%
                                margin-left:-width/2
                                margin-top:-height/2
            */
            position: absolute;
            top: 50%;
            left: 50%;
            margin-left: -50px;
            margin-top: -50px;
        }
    </style>
</head>
<body>
    <div class="parent">
        <div class="child"></div>
    </div>
</body>
</html>