方案
参考
思否 – 15种CSS居中的方式
居中
inline-block + text-align
table + margin
absolute + transform
flex + justify-content
垂直
table-cell + vertial-align
absolute + transform
flex + align-items
水平垂直
inline-block + table-cell + text-align + vertical-align
absolute + transform
flex
多列布局 – 一列定宽,一列自适应
float + margin
float + overflow
table
flex
多列布局 – 多列定宽,一列自适应
float + overflow
table
flex
一列不定宽,一列自适应
float + overflow
table
flex
多列不定宽,一列自适应
float + overflow
- 等分
float + margin
table + margin
flex
等高
float + overflow
table
flex
并排等分,单排对齐靠左布局
flex
圣杯布局&双飞翼布局
居中
inline-block + text-align
tips:此方案兼容性较好,可兼容至IE8,对于IE567并不支持inline-block,需要使用css hack进行兼容
1
2
3
4
5
6.parent{
text-align: center;
}
.child{
display: inline-block;
}table + margin
tips:此方案兼容至IE8,可以使用
代替css写法,兼容性良好
1
2
3
4.child{
display: table;
margin: 0 auto;
}absolute + transform
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21.parent{
position: relative;
height:1.5em;
}
.child{
position: absolute;
left: 50%;
transform: translateX(-50%);
}
/* tips:此方案兼容至IE9,因为transform兼容性限制,如果.child为定宽元素,可以使用以下写法,兼容性极佳 */
.parent{
position: relative;
height:1.5em;
}
.child{
position: absolute;
width:100px;
left: 50%;
margin-left:-50px;
}
垂直
table-cell + vertial-align
可替换成
布局,兼容性良好
1
2
3
4.parent{
display: table-cell;
vertical-align: middle;
}absolute + transform
tips:存在css3兼容问题,定宽兼容性良好
1
2
3
4
5
6
7
8.parent{
position: relative;
}
.child{
position: absolute;
top: 50%;
transform: translateY(-50%);
}flex + align-items
tips:高版本浏览器兼容,低版本不适用
1
2
3
4.parent{
display: flex;
align-items: center;
}
水平垂直居中
已知宽度,负间距
固定宽高元素水平垂直居中,通过margin平移元素整体宽度的一半,使元素水平垂直居中
1
2
3
4
5
6
7
8
9
10
11.parent{
position: relative; /* 已知宽度 */
}
.child{
position: absolute;
top: 50%;
left: 50%;
width: 80%;
height: 60px;
margin: -30px 0 0 -40%;
}absolute + transform
利用2D变换,在水平和垂直两个方向都向反向平移宽高的一半,从而使元素水平垂直居中
1
2
3
4
5
6
7
8
9.parent{
position: relative;
}
.child{
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}flex + justify-content + align-items
1
2
3
4
5.parent {
display: flex;
justify-content: center;
align-items: center;
}inline-block + table-cell + text-align + vertical-align
1
2
3
4
5
6
7
8.parent{
text-align: center;
display: table-cell;
vertical-align: middle;
}
.child{
display: inline-block;
}grid + margin-auto
利用grid实现水平垂直居中,兼容性较差
1
2
3
4
5
6
7.parent {
height: 140px;
display: grid;
}
.child {
margin: auto;
}