美文网首页
垂直居中

垂直居中

作者: 夜月徐风 | 来源:发表于2019-08-05 20:58 被阅读0次

    eg.
    <div class="out" style="width: 200px;height: 200px;background: lightblue;">
    <div class="in" style="width: 50px;height: 50px;background: lightgrey;"></div>
    </div>
    第一种,万能的flex布局
    主要用到弹性盒的align-items: center属性
    .out{
    display: flex;
    align-items: center;
    }
    note:
    使用flex配合margin: auto 可以实现水平垂直都居中
    第二种,使用定位
    对于已知高度:
    即:
    .out {
    position: relative;
    }
    .in {
    top:50%;left: 50%;margin-top: -height/2;margin-left: -width/2;
    或者
    position: absolute;top:calc(50% - height/2); calc(50% - width/2);
    }
    对于未知高度:
    即:
    .out {
    position: relative;
    }
    .in {
    position: absolute;transform:translate(-50%,-50%);
    }
    第三种,使用table
    display: table-cell;ertical-align: middle
    .out{
    display: table-cell;
    vertical-align: middle;
    text-align: center;
    }
    .in {
    display: inline-block;
    }
    note: table-cell不感知table-row等属性

    相关文章

      网友评论

          本文标题:垂直居中

          本文链接:https://www.haomeiwen.com/subject/rcyvdctx.html