- Flex布局(推荐)
.container {
display: flex;
justify-content: center;
align-items: center;
height: 300px;
}
- 绝对定位
2.1 已知子元素宽高
.container {
position: relative;
height: 300px;
}
.child {
position: absolute;
left: 50%;
top: 50%;
width: 200px;
height: 100px;
margin-left: -100px; /* 宽度的一半 */
margin-top: -50px; /* 高度的一半 */
}
2.2 未知子元素宽高
.child {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%); /* 偏移自身宽高50% */
}
- margin auto
.child {
position: absolute;
width: 200px;
height: 100px;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
}
- line-height + text-align
.container {
height: 100px;
line-height: 100px; /* 与容器高度一致 */
text-align: center; /* 水平居中 */
}