常见的垂直水平居中方法
1. position+margin负值的方法(宽高固定)
.box{
position:relative;
width: 500px;
height: 500px;
border: 5px solid red;
}
.item {
position:absolute;
margin-left: -100px;
margin-top: -150px;
left:50%;
top:50%;
width: 200px;
height: 300px;
background-color: #ccc;
}
2. position+margin:auto (固定宽高)
.box{
position:relative;
width: 500px;
height: 500px;
border: 5px solid red;
}
.item {
position:absolute;
margin:auto;
left:0;
right:0;
top:0;
bottom:0;
width: 200px;
height: 300px;
background-color: #ccc;
}
3. display:table-cell + vertical-align:middle (固定宽度)
.box{
display: table-cell;
vertical-align: middle;
width: 500px;
height: 500px;
border: 5px solid red;
}
.item {
margin:auto;
width: 200px;
height: 300px;
background-color: #ccc;
}
4. position+transform(不需要固定宽高)
.box{
position:relative;
width: 500px;
height: 500px;
border: 5px solid red;
}
.item {
position: absolute;
top: 50%;
left: 50%;
transform:translate(-50%,-50%);
width: 200px;
height: 300px;
background-color: #ccc;
}
5. flex (不需要固定宽高)
.box{
display:flex;
justify-content:center;
align-items:center;
width: 500px;
height: 500px;
border: 5px solid red;
}
.item {
width: 200px;
height: 300px;
background-color: #ccc;
}