css水平垂直居中

沧浪之水清兮,可以濯吾缨;沧浪之水浊兮,可以濯吾足。——《渔父》

单行文本:

1
2
3
4
.one{
line-height:100px;
text-align:center;
}

多行文本:

把文字当图片处理,用span包裹,然后处理成图片display:inline-block, 然后父元素设置table-cell

table-cell + verticial-align,父元素 设置为table-cell,子元素设置为 inline-block

1
2
3
4
5
6
7
8
9
10
.parent {
width: 500px;
height: 400px;
display:table-cell;
text-align:center;
vertical-align:middle;
}
.child {
display:inline-block;
}

绝对定位 + 负外边距,兼容性好,缺点是需要 元素大小固定

1
2
3
4
5
6
7
8
9
10
11
12
.parent {
position: relative;
}
.child {
position: absolute;
height: 100px;
width: 200px;
top: 50%;
left: 50%;
margin-top: -50px; //高度、宽度的一半
margin-left: -100px;
}

绝对定位盒模型和margin:0 auto

1
2
3
4
5
6
7
8
9
10
11
12
13
14
.parent{
position:relative;

}
.child{
position:absolute;
top:0;
left:0;
right:0;
bottom:0;
margin:0 auto;
width:100px;
height:200px;
}

绝对定位 + transform

1
2
3
4
5
6
7
8
9
10
.parent {
position: relative;
}
.child {
position: absolute;
top: 50%;
left: 50%;
transform: translateY(-50%);
transform: translateX(-50%);
}

flex

1
2
3
4
5
.parent {
display: flex;
justify-content: center;
align-items: center;
}