工作中经常涉及到盒子水平垂直居中,分别有哪些方式,现在盘点一下?
一、absolute + transform 布局
<div class="box">
<div class="box-sub"></div>
</div>
<style>
.box {
position:relative;
width:160px;
height:160px;
background:red;
}
.box-sub{
position:absolute;
top: 50%;
left: 50%;
z-index:9;
transform:translate(-50%,-50%);
width:80px;
height:80px;
background:green;
}
</style>
![](https://img-blog.csdnimg.cn/7c413432eadc4d3b9afc2e79cfd1a995.png)
二、display:flex 布局
<div class="box">
<div class="box-sub"></div>
</div>
<style>
.box{
width:200px;
height:200px;
background-color:red;
color:white;
font-size:20px;
font-weight:bold;
display:flex;
align-items:center;
justify-content:center;
}
.box-sub {
width:100px;
height:100px;
background:green;
}
</style>
![](https://img-blog.csdnimg.cn/78e85086e5594f4eb8fbf26e8785e106.png)
三、display: grid 布局
<div class="box">
<div class="box-sub">hello world</div>
</div>
<style>
.box {
display: grid;
width:200px;
height:200px;
background-color:red;
color:white;
font-size:20px;
font-weight:bold;
}
.box-sub {
align-self: center;
justify-self: center;
}
</style>
![](https://img-blog.csdnimg.cn/f4365e10f8e24e42b3fbb9322a34f1dd.png)
四、table 布局
<table>
<tbody>
<tr>
<td class="box">
<div class="sub"></div>
</td>
</tr>
</tbody>
</table>
.box {
width:200px;
height:200px;
text-align: center;
background:red;
}
.sub {
display: inline-block;
background:green;
width:100px;
height:100px;
}
![](https://img-blog.csdnimg.cn/617bffee49444cca97430fc39ec14156.png)
虽然还有几种方式可以实现该效果,但存在兼容性,所以这里就不介绍了