子盒子在父盒子中水平垂直居中有几种方法?

Posted by CodingWithAlice on June 29, 2021

子盒子在父盒子中水平垂直居中有几种方法?

<head>
    <style>
        .father {
            width: 800px;
            height: 650px;
        }
        .child {
            width: 300px;
            height: 150px;
        }
    </style>
</head>
<body>
    <div class="father">
        <div class="child">子盒子</div>
    </div>
</body>

1️⃣不需要知道子盒宽高

1.flex布局

/* 父盒子 */
.father {
    display: flex;
    justify-content: center; 
    align-items: center;
}

2.绝对定位 + transform-50%

.father {
    position: relative;
}
/* 子盒子 */
.child {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}
/* 在已知子盒子宽高的情况下, transform 可以改为 margin -> 性能考虑 */
.child {
	margin: -75px 0 0 -150px;
}

3.绝对定位 四个方向0 + margin:auto

.father {
    position: relative;
}
/* 子盒子 */
.child {
    position: absolute;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    margin: auto; /* 四边均衡受力从而实现盒子的居中 */
}

4.table-cell + 文本格式

.father {
    display: table-cell; /* 能够使元素呈单元格的样式显示 */
    vertical-align: middle; /* 内容垂直居中 */
    text-align: center; /* 内容水平居中 */
}
.child {
    display: inline-block; /* 『使其内容变为文本格式,但仍旧可以设置宽高』 */
}

2️⃣ 行内元素的一些居中属性

text-align: center
vertical-align: middle;

line-height: 100px;
height: 100px;

3⃣️ 块元素的一些居中属性

/* 当前元素必须有宽度 */
margin :0 auto