前端经典css面试题:如何让一个div垂直水平居中
<div class="father"> <div class="child"></div> </div>
方法1:flex布局
.father{
display: flex;
justify-content: center;
align-items: center;
}
方法2:定位
.father{
position: relative;
}
/*1.元素宽高未知*/
.child{
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
}
/*2.元素宽高已知*/
.child{
position: absolute;
margin-left: -50px;
margin-top: -25px;
top: 50%;
left: 50%;
width: 100px;
height: 50px;
}
/*或*/
.child{
position: absolute;
margin: auto;
top: 0;
right: 0;
bottom: 0;
left:0;
width: 100px;
height: 50px;
}
网友评论