css实现居中的几种方法
1.通过text-align:center 和line-height:**px 实现单行水平垂直居中
.box{width: 200px;height: 200px;border: 1px solid black;
text-align:center;line-height:200px;}
<div class="box">
我在居中<br />我无法居中
</div>
效果
2.通过在父元素中设置display:table-cell;vertical-align:middle;来实现垂直居中
.box{width: 200px;height: 100px;border: 1px solid black;
display: table-cell;vertical-align: middle;text-align: center;}
<div class="box">
我在居中<br />我也在居中
</div>
效果
注意:
使用table-cell是最好不要与float和position:absolute一起使用,设置了table-cell的元素对高度和宽度敏感,对margin值无反应,可以响应padding的设置,表现几乎类似于一个td元素
3.通过position:absolute;的特性设置各偏移值为0,再设置margin:auto;
.box1{width: 200px;height: 100px;background-color: #059AE3;
position: relative;}
.box2{width: 100px;height: 50px;background-color: white;
position: absolute;
top: 0;left: 0;right: 0;bottom: 0;
margin: auto;}
<div class="box1">
<div class="box2">盒子居中</div>
</div>
同样也可以通过偏移属性和translate()函数的自身偏移来达到同样的效果
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
效果
4.在display: flex;容器下的子元素设置margin:auto;
.box1{width:200px height:100px;border: 1px solid black;
display: flex;}
.box2{margin: auto;}
<div class="box1">
<div class="box2">我在居中</div>
</div>
同样也可以在设置display: flex;的容器上使用
主轴对齐justify-content:center和侧轴对齐align-items:center来达到同样的效果