CSS居中布局

一:水平居中方案:
  1、行内元素
    设置 text-align:center

  2、定宽块状元素
    设置 左右 margin 值为 auto

  3、不定宽块状元素
    a:在元素外加入 table 标签(完整的,包括 table、tbody、tr、td),该元素写在 td 内,然后设置 margin 的值为 auto
    b:给该元素设置 displa:inine 方法
    c:父元素设置 position:relative 和 left:50%,子元素设置 position:relative 和 left:50%

  4、对于多个块级元素:
    对父元素设置 text-align: center;
    对子元素设置 display: inline-block;

  5、使用 flex 布局


二:垂直居中设置

  1、行内元素
    单行:
      设置上下 pandding 相等;
      或者设置 line-height 和 height 相等

    多行:
      设置上下 pandding 相等;
      父元素设置 display: table-cell; 和 vertical-align: middle;
      或者使用 flex 布局;

  2、块级元素:下面前两种方案,父元素需使用相对布局
    父元素已知高度:子元素使用绝对布局 top: 50%,再用负的 margin-top 把子元素往上拉一半的高度;
    父元素未知高度:子元素使用绝对布局 position: absolute; top: 50%; transform: translateY(-50%);
    使用 Flexbox:选择方向,justify-content: center;

三:水平垂直居中

  定高定宽:
    先用绝对布局 top: 50%; left: 50%;,再用和宽高的一半相等的负 margin 把子元素回拉;

  高度和宽度未知:
    先用绝对布局 top: 50%; left: 50%;,再设置 transform: translate(-50%, -50%);

  使用 Flexbox:
    justify-content: center; align-items: center;

原文地址:https://www.cnblogs.com/lishuxue/p/6433411.html