那么不知道两个盒子各自宽高的情况下,怎么实现子盒子的垂直居中呢
首先定义两个盒子,蓝色是爸爸,绿色是儿子
<div class="parent" id="parent">
    <div class="child" id="child"></div>
</div>
<style>
    .parent{
        width: 200px;
        height: 200px;
        background: rgb(108, 175, 238);
    }
    .child{
        width: 50px;
        height: 50px;
        background: rgb(177, 235, 166);
    }
</style>
方法1. 利用display: flex/grid
.parent {
    display: flex;
    justify-content: center;
    align-items: center;
}
方法2: 利用display: grid
.parent{
    display:grid;
    place-items: center;
}
注意:此方法等同于方法1,place-items: center是justify-content: center和align-items: center的简写
方法3: 利用display: flex/grid和margin: auto
.parent {
    display: flex;
}
.child {
    margin: auto;
}
或者
.parent {
    display: grid;
}
.child {
    margin: auto;
}
方法4. 利用transform
.parent{
    position:relative;
}
.child{
    position:absolute;
    top:50%;
    left:50%;
    transform:translate(-50%,-50%);
}
方法5. 利用 position和margin: auto
.parent {
    position: relative;
}
.child {
    position: absolute;
    margin: auto;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
}
注意:此方法子盒子必须要有具体宽高值