盒子垂直水平居中的常用方式
基础html布局
<div class="box">
<div class="item"></div>
</div>
css
flex布局
.box{
height: 300px;
width:400px;
border: 1px solid black;
display: flex;
justify-content: center;
align-items: center;
}
.box .item{
height: 200px;
width:200px;
background: blue;
}
position 1
.box{
height: 300px;
width:400px;
border: 1px solid black;
position: relative;
}
.box .item{
position: absolute;
height: 200px;
width:200px;
background: blue;
top: 0;
bottom: 0;
right: 0;
left: 0;
margin:auto;
}
position 2
.box{
height: 300px;
width:400px;
border: 1px solid black;
position: relative;
}
.box .item{
position: absolute;
height: 200px;
width:200px;
background: blue;
top: 50%;
left: 50%;
margin-left: -100px;//自身宽度的一半
margin-top:-100px;//自身高度的一半
}
position+translate
.box{
height: 300px;
width:400px;
border: 1px solid black;
position: relative;
}
.box .item{
position: absolute;
height: 200px;
width:200px;
background: blue;
top: 50%;
left: 50%;
transform:translate(-50%,-50%);
}
table-cell
.box{
height: 300px;
width:400px;
border: 1px solid black;
display: table-cell;
vertical-align:middle;
text-align: center;
}
.box .item{
height: 200px;
width:200px;
background: blue;
display: inline-block;
}