天天看點

CSS水準垂直居中方案【前端面試必備!!】

CSS水準垂直居中方案【前端面試必備!!】

1、單行文本

div {
    height:100px;
    line-height: 100px;
    text-align: center;
 }
           

2、定高(position + margin) —— 前提是父級要有高度

div {
    position: absolute;
    height: 100px;
    top: 50%;
    left: 50%;
    margin: -50px 0 0 -50px;
}
           

3、不定高(position+transform) —— 前提是父級要有高度

div {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}
           

4、不定高(flex)—— 推薦

div {
    display: flex;
    align-item: center;
    justify-content: center;
}
           

5、不定高(table)

.parent{
    display: table-cell;
    text-align: center;
    .child {
         vertical-align: middle;        
    }
}