垂直居中

【逆天大总结系列】

垂直居中这件事情实在是快嚼烂了,总结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;
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容