让盒子实现垂直居中和水平居中

让盒子实现垂直居中和水平居中



代码:

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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .father {
            position: relative;
            width: 300px;
            height: 300px;
            background-color: #bfa;
        }

        .son {
            position: absolute;
            width: 200px;
            height: 200px;
            background-color: pink;
            top: 50%;
            left: 50%;

            /* 以前的做法,需要获得具体的子盒子的尺寸 */
            /* margin-top: -100px;
            margin-left: -100px; */

            /* 新的方法,不必知道尺寸 */
            transform: translate(-50%, -50%);
        }
    </style>
</head>

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

</html>

效果图:
在这里插入图片描述
注意:

发布了11 篇原创文章 · 获赞 0 · 访问量 448

猜你喜欢

转载自blog.csdn.net/qq_36323561/article/details/105088172