css - 垂直水平居中
本文概览
- Flex 布局(推荐)
- 绝对定位 + transform
- Grid 布局
- 表格布局
- margin auto(已知宽高)
1.Flex 布局(推荐)
.parent {
display: flex;
justify-content: center;
align-items: center;
}
2.绝对定位 + transform
.parent {
position: relative;
}
.child {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
3.Grid 布局
.parent {
display: grid;
place-items: center;
}
4.表格布局
.parent {
display: table-cell;
vertical-align: middle;
text-align: center;
}
.child {
display: inline-block;
}
5.margin auto(已知宽高)
.parent {
position: relative;
}
.child {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
width: 100px;
height: 100px;
}