手写垂直水平居中
- 第一种方法: position+margin负值的方法(宽高固定)
.box {
position: relative;
width: 500px;
height: 500px;
border: 5px solid red;
}
.item {
position: absolute;
left: 50%;
top: 50%;
margin-top: -150px;
margin-left: -100px;
width: 200px;
height: 300px;
background-color: pink;
}
- 第二种方法:position+margin:auto (固定宽高)
.box {
width: 500px;
height: 500px;
border: 5px solid red;
position: relative;
}
.item {
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
margin: auto;
width: 200px;
height: 200px;
background-color: pink;
}
- 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: 200px;
background-color: pink;
}
- 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: 200px;
background-color: pink;
}
- flex (不需要固定宽高)
.box {
display: flex;
justify-content: center;
align-items: center;
width: 500px;
height: 500px;
border: 5px solid red;
}
.item {
width: 200px;
height: 200px;
background-color: pink;
}