垂直居中的几种实现方式

垂直居中.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;
    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容