【逆天大总结系列】
垂直居中这件事情实在是快嚼烂了,总结ta宝宝也是下了很大决心的。。。
什么情况下能做到水平居中
- inline或inline-block的元素,给他爹设置
text-align: center; - 一个block的元素,自己设置
margin: auto; - 多个block的元素,要么让他爹用
display: flex; justify-content: center;要么自己设置成inline-block然后让爹text-align:center
什么情况下能做到垂直居中
- 不超过一行的文本,height == line-height可以做到
- 文本多行情况:使用table布局;或者自己设置
display:table-cell;verticle-align:middle&& 它爹设置display:table; - block高度已知,
top: 50%, margin-top: -height/2 - block高度未知,
top:50%, transform: translateY(-50%) - 牛B的flex,它爹设置
display: flex; justify-content: center; flex-direction: column;
超好用的水平垂直都居中(他爹relative, 他自己absolute)
- 固定宽高:
left: 50%; top: 50%; margin-left: -width/2; margin-top: -height/2; - 不固定宽高:
left: 50%; top: 50%; transform: translateX(-50%) translateY(-50%); - flex:
他爹设置display: flex; justify-content: center; align-items: center; -
宝宝喜欢用这种:
margin: auto; left: 0; right: 0; top: 0; bottom: 0;