csss实现水平垂直居中的方法大全


1. 水平居中

  • 1.1 行内元素
  • (1) text-align:center
  • 1.2 块级元素
  • 确定宽度
    (1) margin:0 auto;
    (2) 子绝父相 + margin-left:-自己width/2
  • 未知宽度
    (4) display:inline-block; text-align:center
    (5) 子绝父相 + translateX(-50%)
    (6) display:table;margin:0 auto;
    (7) display:flex; justify-content:center

2. 垂直居中

  • vertical-align:middle(内联元素/display:table-cell)
  • line-height(适合纯文本)
  • 子绝父相 + left:0;right:0 + margin:auto;(设置宽)
  • 子绝父相 + top + translateY
  • display:flex; margin:auto;

重点:
W3C规定,top,bottom设置为auto,其实默认值为0。margin:auto; == margin:0 auto;只是水平居中
W3C规定,只有绝对定位的元素才可以使用top,bottom为auto的自动分配从而实现上下左右都自动分配margin。但是前提要设置top,bottom,left,right为0,使得元素找到边界,margin也可以找到边界去auto分配外边距,从而实现水平垂直居中。

参考文章:
1.margin:auto不能实现垂直居中
2.margin: 0 auto 水平居中原理

猜你喜欢

转载自blog.csdn.net/puhuihui/article/details/125352015