CSS垂直水平居中总结

CSS垂直水平居中是一个经常需要面对的问题,也是一个面试常考的问题 0.0

单行文本水平垂直居中 text-align + line-height

1
2
3
4
5
p{
text-align:center;
height:20px;
line-height:20px;
}

使用相对定位垂直居中 1 margin + relative

1
2
3
4
5
6
7
8
//适用于已知宽高的
div{
height:300px;
margin:0 auto; //水平居中
position:relative;
top:50%;
margin-top:-150px;//垂直居中
}

使用相对定位垂直居中 2 translate + relative

1
2
3
4
5
6
7
//适用于宽高未知的
div{
margin:0 auto;
position:relative;
top:50%;
transform:translateY(-50%);//使用CSS3的偏移属性实现垂直居中
}

使用绝对定位垂直居中 absolute

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
parent{
positive:relative;
}
//有两种实现方法
child{
height:50px;
width:80px;
position:absolute;
left:0;right:0;
top:0;bottom:0;
margin:auto;
}
child{
position:absolute;
top:50%;
left:50%;
transform:translate(-50%,-50%)
}

使用弹性布局

1
2
3
4
5
div{
display:flex;
align-items:center;
justify-contents:center;
}

以上方法都可以自由组合,灵活运用,是情况使用