前端經(jīng)典css面試題:如何讓一個(gè)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;
}