关于div水平垂直居中的几种方法

Dom结构:

<div class="box">
        <div class="inner">
            123
        </div>
</div>

 

 

1, 伪元素 加 vertical-align 

       .box {
            width: 300px;
            height: 300px;
            border: 1px solid red;
            text-align: center;
        }
        .box:before{
            content: '';
            height: 100%;
            width: 0;
            display: inline-block;
            vertical-align: middle;
        }
        .inner{
            display: inline-block;
        }

 

2, table -ceil

        .box {
            width: 300px;
            height: 300px;
            border: 1px solid red;
            display: table-cell;
            vertical-align: middle;
            text-align: center;
        }    

 

3, flex

         .box {
            width: 300px;
            height: 300px;
            border: 1px solid red;
            display: flex;
            justify-content: center;
            align-items: center;
        }
    

 

4, transform  

        .box {
            width: 300px;
            height: 300px;
            border: 1px solid red;
            position:relative;
        }
        .inner{
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
        }

 

5, absolute + margin:auto  (子元素要设置宽高)

        .box {
            width: 300px;
            height: 300px;
            border: 1px solid red;
            position:relative;
        }
        .inner{
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            width: 100px;
            height: 100px;
            margin: auto;
        }

 

6, flex + margin:auto

        .box {
            width: 300px;
            height: 300px;
            border: 1px solid red;
            display: flex;
        }
        .inner{
            margin: auto;
        }

 

posted @ 2019-08-21 16:29  ken丶123  阅读(190)  评论(0编辑  收藏  举报