css垂直居中

css水平居中很容易实现,如果是行内元素,直接使用text-align:center,如果是块元素,则可以marin-left:auto;margin-right:auto;来实现。

垂直居中是前端开发中极其常见的需求,理论上很简单,实践起来却有难度。常用的有以下几种方法:

html格式:

 

<div class="out-box">
        <div class="inner-box">
            <p>inner text</p>
            <h5>inner title</h5>
        </div>
    </div>

 

 

 

1.基于绝对定位的方案

.out-box{
            width: 200px;
            height: 200px;
            background: yellow;
            margin: 50px auto;
            position: relative;
        }
        .inner-box{
            width: 80px;
            height: 100px;
            background: blue;
            position: absolute;
            left: 50%;
            top: 50%;
            transform: translate(-50%,-50%);
       color:#fff;
       text-align:center;
}

效果如图:

2.基于flexbox的解决方案

.out-box{
            width: 200px;
            height: 200px;
            background: yellow;
            margin: 50px auto;
            display: flex;
        }
        .inner-box{
            background: blue;
            margin: auto;
            color: #fff;
            text-align: center;
        }

效果如图所示:

 

posted @ 2018-02-21 22:42  shuangcherry  阅读(114)  评论(0编辑  收藏  举报