美文网首页
垂直居中的几种实现方式

垂直居中的几种实现方式

作者: YucinChow | 来源:发表于2019-05-12 11:41 被阅读0次
垂直居中.png

上图中从大到小分别为div1,div2,div3

  <div class="div1">
        <div class="div2">
            <div class="div3">
                垂直居中
            </div>
        </div>
    </div>

使用position,transfrom实现垂直居中

       .div1{
            position: relative;
            width: 300px;
            height: 300px;
            background-color: cyan;
        }
        .div1 .div2{
            display: flex;
            flex-direction: column;
            justify-content: center;
            position: absolute;
            top: 50%;
            width: 200px;
            height: 200px;
            background-color: greenyellow;
            transform: translateY(-50%);
        }

在已知div2宽高的情况下,可以使用position和marginTop来实现

     .div1{
            position: relative;
            width: 300px;
            height: 300px;
            background-color: cyan;
    }
    .div1 .div2{
            display: flex;
            flex-direction: column;
            justify-content: center;
            position: absolute;
            top: 50%;
            margin-top: -100px;
            width: 200px;
            height: 200px;
            background-color: greenyellow;
    }

使用flex, flex-direction,justify-content,实现垂直居中,使用line-height让单行文字垂直居中

     .div1 .div2{
            display: flex;
            flex-direction: column;
            justify-content: center;
            position: absolute;
            top: 50%;
            width: 200px;
            height: 200px;
            margin-top: -100px;
            background-color: greenyellow;
        }
        .div2 .div3{
            width: 100px;
            height: 100px;
            line-height: 100px;
            background-color: orange;
        }

使用vertical-align垂直表格单元内容

       <table class="table">
           <tbody>
                 <tr>
                   <td>垂直居中</td>
                 </tr>
           </tbody>
       </table>
    .table td{
            width: 100px;
            height: 100px;
            vertical-align: middle;
            background-color: violet;
    }

相关文章

网友评论

      本文标题:垂直居中的几种实现方式

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