假设有两个盒子,不知道子盒子的宽高
<div class="container">
<div class="box"></div>
</div>
要实现的效果如下:
第一种方法:
.container {
display: flex;
justify-content: center;
align-items: center;
}
第二种:
.container {
position: relative;
}
.box {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
第三种:
.container {
position: relative;
}
.box {
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
margin: auto;
}
第四种:
.container {
display: table-cell;
text-align: center;
vertical-align: middle;
}
.box {
display: inline-block;
}
第四种方法会导致父元素四个方向上的margin失效。