前言
说到底就是三种咯:1.定位+transform 2.弹性盒子 3.dispaly: table
css多种 水平垂直 居中方式
- 下面介绍弹性盒子,自适应,的水平垂直居中方式
1.left:0; right:0; top:0; bottom:0;居中
#box{
width: 150px;
height: 150px;
border: 1px solid #FF0000;
position: relative;
}
#box #text{
width: 50px;
height: 50px;
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
margin: auto;
background: #ccc;
}
<div id="box">
<div id="text"> </div>
</div>
2.display: flex 居中
#box{
width: 150px;
height: 150px;
border: 1px solid #FF0000;
display: flex;
justify-content: center;
align-items: center;
}
#box #text{
width: 50px;
height: 50px;
background: #ccc;
}
<div id="box">
<div id="text"> </div>
</div>
3.transform:translate 居中
#box{
width: 150px;
height: 150px;
border: 1px solid #FF0000;
position: relative;
}
#box #text{
width: 50px;
height: 50px;
background: #ccc;
position:absolute;
left:50%;
top:50%;
transform:translate(-50%,-50%);
}
<div id="box">
<div id="text"> </div>
</div>