居中

94 阅读2分钟

水平居中

前置条件:

  • 父元素必须是块级盒子容器
  • 父元素宽度必须已经被设定好
    <div class="father">
    [这里放未知的子元素]
    </div>

场景一:子元素是 块元素 + 宽度未设定

不存在水平居中 原因:子元素是块元素,会充满整个父级元素宽度

场景二:子元素是 行内元素

    .father { text-align: center }

场景三:子元素是 块元素 + 宽度已设定

  • 方法一
.son { margin: 0 auto }
  • 方法二
# 现在已经知道了父元素宽度和子元素宽度,通过计算就可以了
# margin-left 或 margin-right 或 padding-left 或 padding-right
  • 方法三 通过绝对定位,transform方式
    .father { position: relative }
    .son {
        position: absolute;
        left: 50%;
        margin-left: 子元素宽度的一半 或者 translateX(-50%);
     }
  • 方法四 利用flex弹性布局
    .father {
        display: flex;
        justify-content: center
    }

垂直居中

前置条件

  • 父元素是盒子容器
场景一:子元素是行内元素

子元素高度是由其内容撑开的

  • 单行:设定父元素的line-height为其高度来使得子元素垂直居中
.father { line-height: 【高度】 }  // 单行
  • 多行:通过父元素设定
.father {
    display: inline/inline-block/table-cell;
    verticel-align:middle;
}

场景二:子元素是块元素,高度未定

  • 方法一
    .father {
        display: inline/inline-block/table-cell;
        vertical-align:middle;
    }
  • 方法二:flex
    .father {
        display: flex;
        flex-direction: column;
        justify-content: center;
    }

场景三:子元素是块元素,高度已定

  • 方法一 通过计算 margin-top/margin-bottom/padding-top/padding-bottom
  • 方法二 通过绝对定位
.son {
    top: 50%;
    margin-top: 子高一半
}
  • 方法三 利用translate
.son {
    top: 50%;
    transform: translateY(-50%)
}
  • 方法四 利用flex
.father {
    display: flex;
    flex-direction: column;
    justify-content: center;
}

水平垂直居中

  • 父相对位置,子绝对
    top: 50%;
    left: 50%;
    transform:translate(-50%, -50%); // 未知子元素宽高的情况
    // 或 已知宽高
    margin-left: 子宽一半
    margin-top: 子高一半
  • 弹性布局
    .father {
        display: flex;
        justify-content: center;
        align-items: center;
    }