SOURCE

console 命令行工具 X clear

                    
>
console
<div class="parent1">
	<div class="child1"></div>
</div>

<div class="parent2">
	<div class="child2"></div>
</div>

<div class="parent3">
    <div class="child3"></div>
</div>

<div>
	<div class="parent4">
		<div class="child4"></div>
	</div>
</div>

<div class="parent5">
    <div class="child5"></div>
</div>
body {
    display: flex;
    margin: 0;
}

/* 1. 绝对定位 + 负外边距 */
.parent1 {
    position: relative;
    width: 200px;
    height: 200px;
    border: 1px solid;
}

.child1 {
    position: absolute;
    top: 50%;
    left: 50%;
    width: 100px;
    height: 100px;
    margin: -50px -50px;
    background-color: #f90;
}

/* 2. 绝对定位 + translate */
.parent2 {
    position: relative;
    width: 200px;
    height: 200px;
    border: 1px solid;
}

.child2 {
    position: absolute;
    top: 50%;
    left: 50%;
    width: 100px;
    height: 100px;
    background-color: #669;
    transform: translate(-50%, -50%);
}

/* 3. 绝对定位 + trbl: 0; margin: auto; */
.parent3 {
    position: relative;
    width: 200px;
    height: 200px;
    border: 1px solid;
}

.child3 {
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    width: 100px;
    height: 100px;
    margin: auto;
    background-color: #369;
}

/* 4. 父:table-cell + vertical-align 垂直居中
      子:margin: 0 auto; 水平居中
      注:有时会受flex布局影响,可以再外层套个壳
 */
.parent4 {
    display: table-cell;
    width: 200px;
    height: 200px;
    border: 1px solid;
    vertical-align: middle;
}

.child4 {
    width: 100px;
    height: 100px;
    margin: 0 auto;
    background-color: #699;
}

/* 5. 父:font-size: 0; text-align: center;
      伪: dib, vertical: middle;
      子:dib, vertical: middle;
 */
.parent5 {
    width: 200px;
    height: 200px;
    border: 1px solid;
    font-size: 0;
    line-height: 200px;
    text-align: center;
}

.parent5::before {
    display: inline-block;
    vertical-align: middle;
    content: "";
}

.child5 {
    display: inline-block;
    width: 100px;
    height: 100px;
    vertical-align: middle;
    background-color: #99f;
}