让一个元素水平垂直居中的方式:
1. 定位+margin
.father{
width: 400px;
height: 400px;
border: 1px solid;
position: relative;
}
.son{
width: 200px;
height: 200px;
position: absolute;
background-color: #bfa;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
}
2. 定位+transform
.father{
width: 400px;
height: 400px;
border: 1px solid;
position: relative;
}
.son{
width: 200px;
height: 200px;
position: absolute;
background-color: #bfa;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
3. flex布局
.father{
width: 400px;
height: 400px;
border: 1px solid;
display: flex;
justify-content: center;
align-items: center;
}
.son{
width: 200px;
height: 200px;
background-color: #faf;
}
效果图:
4. grid布局
5. table布局