工作中常用的使容器垂直、水平居中的方法,也是面试中常考的问题,在此归结为4类:
<!-- 公用html代码 -->
<div class="parent">
<div class="child"></div>
</div>
方案一:使用flex布局
.parent{
width:3rem;
height:5rem;
background: #eee;
display: flex; // 弹性盒子
justify-content: center; // 水平方向居中显示
align-items: center; // 垂直方向居中显示
}
.child{
width:2rem;
height:2rem;
background:pink;
}
方案二:使用posiiton定位
.parent{
width:3rem;
height:5rem;
background: #eee;
position:relative; // 父容器相对定位
}
.child{
width:2rem;
height:2rem;
background:pink;
position:absolute; // 子容器绝对定位
top: 50%;
left: 50%;
margin-top: -1rem;
margin-left: -1rem; // 知道容器宽、高情况下
// transform: translate(-50%, -50%); // 不知道宽、高情况下
}
方案三:使用table-cell + vertical-align: middle
.parent{
width:3rem;
height:5rem;
background: #eee;
display: table-cell;
vertical-align: middle; // 父容器设置元素居中对齐
text-align: center;
}
.child{
display: inline-block; // 这里必须设置为行内块元素显示,vertical-align对块元素不生效
width:2rem;
height:2rem;
background:pink;
vertical-align: middle; // 子容器设置居中对齐
}
方案四:使用grid栅格
.parent{
width:3rem;
height:5rem;
background: #eee;
display: grid; // 如容器设置栅格
}
.child{
width:2rem;
height:2rem;
background:pink;
margin: auto; // 子容器设置margin
}
以上方案展示效果如下: