因为CSS垂直居中在面试中问的实在太多了,我已经把常用的都答了还不依不饶,我真的一滴都没有了,所以做了一个总结,区分为常用的和不常用的.
测试用例:
<div class="father">
<div class="son size">abc</div>
</div>
.father {
border: 1px solid red;
width: 300px;
height: 300px;
}
.son {
background: green;
}
.son.size{
width: 100px;
height: 100px;
}
常用CSS垂直居中:
1.亲爹flex:
没什么好说的,flex就是神,不需要知道子元素的宽高,简单粗暴. 父元素:
.father {
display: flex;
justify-content: center;
align-items: center;
}
2.子绝父相+margin负值:
绝对定位百分比是相对于父元素的宽高,这样可以使使子元素居中,但要注意,此时居中的是子元素的左上角,所以要往回移动子元素的一半宽高,但缺点是要知道子元素的宽高.
.father {
position: relative;
}
.son {
position: absolute;
top: 50%;
left: 50%;
margin-left: -50px;
margin-top: -50px;
}
3.子绝父相+margin:auto:
这种方式通过设置各个方向的距离都是0,此时再将margin设为auto,就可以在各个方向上居中了.
.father {
position: relative;
}
.son {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
}
4.子绝父相+calc:
子绝父相只是一个壳子,既然负margin值可以,那么用calc计算属性也可以,缺点同样是要知道子盒子元素的宽高.
.father {
position: relative;
}
.son {
position: absolute;
top: calc(50% - 50px);
left: calc(50% - 50px);
}
5.子绝父相+transform:translate:
反正移动子元素,那么css的transform属性也可以实现,但transform的translate属性设置百分比时是依照自身宽高的,所以向左上移动50per直接-50%就ok.
.father {
position: relative;
}
.son {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
不常用CSS垂直居中:
1.table做布局已经很少用了,知道即可,如果遇到了清朝遗老代码至少知道这是个啥.
<table>
<tbody>
<tr>
<td class="father">
<div class="son">abc</div>
</td>
]</tr>
</tbody>
</table>
.father {
text-align: center;
}
.son {
display: inline-block;
}
2.table-cell属性
和table原理一致,但写法简单很多.
.father {
display: table-cell;
text-align: center;
vertical-align: middle;
}
.son {
display: inline-block;
}
3.grid
grid一般拿来做flex不方便实现的布局,而不是专门用来做垂直居中,但可以实现.
.father {
display: grid;
}
.son {
align-self: center;
justify-self: center;
}
行内元素垂直居中
把box设置为行内元素,通过text-align就可以做到水平居中,通过vertical-align也可以在垂直方向做到居中.
.father {
line-height: 300px;
text-align: center;
font-size: 0px;
}
.son {
font-size: 16px;
display: inline-block;
vertical-align: middle;
line-height: initial;
text-align: left;
}