如何实现元素水平垂直居中?有哪些方法?
方法 1:Flex(推荐)
.parent {
display: flex;
justify-content: center;
align-items: center;
}
方法 2:Grid
.parent {
display: grid;
place-items: center;
}
方法 3:绝对定位 + transform
.child {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
方法 4:绝对定位 + margin auto
.child {
position: absolute;
top: 0; right: 0; bottom: 0; left: 0;
margin: auto;
width: 200px;
height: 100px;
}
方法 5:绝对定位 + 负 margin
.child {
position: absolute;
top: 50%;
left: 50%;
width: 200px;
height: 100px;
margin-top: -50px;
margin-left: -100px;
}
方法 6:table-cell
.parent {
display: table-cell;
text-align: center;
vertical-align: middle;
}
.child { display: inline-block; }
方法 7:line-height(单行文本)
.parent {
text-align: center;
line-height: 200px;
}
各方法适用场景
| 方法 |
需要固定宽高 |
代码量 |
兼容性 |
| Flex |
❌ |
少 |
IE10+ |
| Grid |
❌ |
最少 |
IE 不支持 |
| transform |
❌ |
少 |
IE9+ |
| margin auto |
✅ |
中 |
好 |
| 负 margin |
✅ |
中 |
好 |
同分类其他题目