垂直居中的幾種實現(xiàn)方式

垂直居中.png

上圖中從大到小分別為div1,div2,div3

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

使用position,transfrom實現(xiàn)垂直居中

       .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來實現(xiàn)

     .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,實現(xiàn)垂直居中,使用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垂直表格單元內(nèi)容

       <table class="table">
           <tbody>
                 <tr>
                   <td>垂直居中</td>
                 </tr>
           </tbody>
       </table>
    .table td{
            width: 100px;
            height: 100px;
            vertical-align: middle;
            background-color: violet;
    }
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容