Summary of the method of centering the child box in the horizontal and vertical directions of the parent box

Statement: The following content is a summary of personal study, the original intention is to facilitate their own study and review records. If there are any errors, please correct me!

To achieve the effect (let the green box (child box) be displayed in the middle of the red box (parent box)):

Insert picture description here

1. Positioning: Son and Father

In general, the child box uses absolute positioning, and the parent box uses relative positioning . Just add a little other code.
method 1:

<!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>
        .box1 {
     
     
            width: 800px;
            height: 500px;
            border: 1px solid red;
            /* 父盒子相对定位,占据位置 */
            position: relative;
        }
        
        .box2 {
     
     
            width: 300px;
            height: 150px;
            border: 1px solid green;
            /* 子盒子绝对定位,不占据位置 */
            position: absolute;
            /*子盒子相对于父盒子的宽和高移动50%(即移动宽和高为父盒子的50%)  */
            top: 50%;
            left: 50%;
            /* 再回退到自身盒子宽和高的一半(由于坐标原点在左上角,向右移动为正值,向左移动为负值,所以这里为负值) */
            margin-left: -150px;
            margin-top: -75px;
        }
    </style>
</head>

<body>
    <div class="box1">
        <div class="box2"></div>
    </div>
</body>

</html>

Method 2: Using translate in css3, there is no need to calculate the width and height of the child box, because the moving width and height are calculated relative to its own width and height.
Insert picture description here
Method 3: Set top, right, bottom, and left of the child box to 0, and set the margin to auto
Insert picture description here

2.flex layout

<!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>
        .box1 {
     
     
            width: 800px;
            height: 500px;
            border: 1px solid red;
            /* flex布局默认主轴是 x 轴 row */
            display: flex;
            /* 设置子元素在主轴上居中对齐 */
            justify-content: center;
            /* 设置子元素在侧轴上居中对齐 */
            align-items: center;
        }
        
        .box2 {
     
     
            width: 300px;
            height: 150px;
            border: 1px solid green;
        }
    </style>
</head>
<body>
    <div class="box1">
        <div class="box2"></div>

    </div>
</body>
</html>

Guess you like

Origin blog.csdn.net/pilgrim_121/article/details/111311678