如何让一个div在垂直水平方向上居中对齐?
方法一:使用transform
.parent {
background-color: #fff;
width: 400px;
height: 400px;
}
.son {
position: relative;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background-color: pink;
}
方法二: flex弹性布局
.parent {
display: flex;
justify-content: center;
align-items: center;
width: 400px;
height: 400px;
background-color: #fff;
}
.son {
background-color: pink;
}
方法三: 绝对定位
.parent {
position: relative;
width: 400px;
height: 400px;
background-color: #fff;
}
.son {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
background-color: pink;
}