不知宽高的父子盒子,子盒子在父盒子中水平垂直居中
- 使用Flexbox布局:
.parent {
display: flex;
justify-content: center;
align-items: center;
}
- 使用绝对定位和transform属性:
.parent {
position: relative;
}
.child {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
- 使用表格布局:
.parent {
display: table;
width: 100%;
height: 100%;
}
.child {
display: table-cell;
vertical-align: middle;
text-align: center;
}
- 使用网格布局:
.parent {
display: grid;
place-items: center;
}
.child {
justify-self: center;
align-self: center;
}