关于div水平垂直居中的几种方法

Dom结构:

<div class="box">
<div class="inner">
123
</div>
</div>

1, 伪元素 加 vertical-align

       .box {
width: 300px;
height: 300px;
border: 1px solid red;
text-align: center;
}
.box:before{
content: '';
height: 100%;
width:;
display: inline-block;
vertical-align: middle;
}
.inner{
display: inline-block;
}

2, table -ceil

        .box {
width: 300px;
height: 300px;
border: 1px solid red;
display: table-cell;
vertical-align: middle;
text-align: center;
}

3, flex

         .box {
width: 300px;
height: 300px;
border: 1px solid red;
display: flex;
justify-content: center;
align-items: center;
}

4, transform

        .box {
width: 300px;
height: 300px;
border: 1px solid red;
position:relative;
}
.inner{
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}

5, absolute + margin:auto  (子元素要设置宽高)

        .box {
width: 300px;
height: 300px;
border: 1px solid red;
position:relative;
}
.inner{
position: absolute;
top:;
left:;
right:;
bottom:;
width: 100px;
height: 100px;
margin: auto;
}

6, flex + margin:auto

        .box {
width: 300px;
height: 300px;
border: 1px solid red;
display: flex;
}
.inner{
margin: auto;
}
上一篇:Yii框架和Vue的完美结合完成前后端分离项目


下一篇:CSS多行文字垂直居中的两种方法