关于flex:4种常见方式带你实现元素水平垂直居中

7次阅读

共计 985 个字符,预计需要花费 3 分钟才能阅读完成。

 咱们在进行页面布局时,元素程度垂直居中是必备的布局形式之一,那么上面咱们来总结四种咱们常见的程度垂直居中的形式,你经常应用哪种呢?

html 对立代码

    <div class="out">
        <div class="inner">

        </div>
    </div>

table-cell 布局

 css 代码

    .out{
          width: 400px;
          height: 400px;
          background-color: pink;
          display: table-cell;
          vertical-align: middle;
      }
      .inner{
          width: 200px;
          height: 200px;
          background-color: #bfa;
          margin: 0 auto;
      }

相对定位 +margin:auto;

        .out{
            width: 400px;
            height: 400px;
            background-color: pink;
            position: relative;
        }
        .inner{
            width: 200px;
            height: 200px;
            background-color: #bfa;
            position: absolute;
            top: 0;
            right: 0;
            bottom: 0;
            left: 0;
            margin: auto;
        }

相对定位 + 负 magin 或 2d 转换

.out{
            width: 400px;
            height: 400px;
            background-color: pink;
            position: relative;
        }
        .inner{
            width: 200px;
            height: 200px;
            background-color: #bfa;
            position: absolute;
            left: 50%;
            top: 50%;
            /* 应用负 margin 与 2d 转换皆可 */
            /* margin-left: -100px;
            margin-top: -100px; */
            transform: translate(-50%,-50%);
        }

flex 布局

 应用 flex 布局此时要留神兼容问题

         .out{
            width: 400px;
            height: 400px;
            background-color: pink;
            display: flex;
            justify-content: center;
            align-items: center;
        }
        .inner{
            width: 200px;
            height: 200px;
            background-color: #bfa;
        }

 
对于实现元素程度垂直居中的四种形式的分享就到这啦。

正文完
 0