CSS-元素居中方案总结

98 阅读1分钟

水平居中:

  1. 行内级元素:

    • 设置父元素的text-align: center
  2. 块级元素:

    • 设置当前块级元素(宽度) margin: 0 auto;
  3. 绝对定位

    • 元素有宽度情况下, left0/right0/margin: 0 auto;
  4. flex

    • justify-content: center

垂直居中:

  1. 绝对定位

    • 元素有高度情况下, top0/bottom0/margin: auto 0;

    • 弊端:
      • 必须使用定位(脱离标准流)
      • 必须给元素设置高度
  2. flex布局(父元素设置flex)

    • align-items: center;
    • 弊端:
      • 当前flex局部中所有的元素都会被垂直居中
      • 相对来说, 兼容性差一点点(基本可以忽略)
  3. top/translate

    /* 两件事情:
      1.让元素向下位移父元素的50%
      2.让元素向上位移自身的50% 
    */
    position: relative;
    top: 50%;
    transform: translate(0, -50%);