# 简介
居中的几类情况:
- 绝对居中定位
- 负边距居中
- Transform 定位
- Flexbox 布局
- table-cell 居中
- font-size 配合 vertical-align 实现垂直居中
- 文本内容居中
# 绝对居中定位
.parent {
position: relative;
}
.child {
/*fixed is ok*/
position: absolute;
width: 100px;
top: 0;
right: 0;
bottom: 0;
left: 0;
margin:auto;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
2
3
4
5
6
7
8
9
10
11
12
13
# 负边距居中
.child {
position: relative;
float: left;
width: 100px;
left: 50%;
top: 50%;
margin-top: -50px;
margin-left: -50px;
}
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
# CSS3 transform
.parent {
position: relative;
}
.child {
position: absolute;
left: 50%;
top: 50%;
transform: translateX(-50%) translateY(-50%);
}
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
# flex
.parent {
display: flex;
justify-content: center;
align-items: center;
}
1
2
3
4
5
2
3
4
5
# table-cell 居中
.parent {
display: table-cell;
vertical-align: middle;
text-align: center;
width: 200px;
height: 200px;
border: 1px solid red;
}
.child {
width: 100px;
height: 100px;
display: inline-block;
background-color: #03f;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
2
3
4
5
6
7
8
9
10
11
12
13
14
.parent {
font-size: 175.4px;
height: 200px;
text-align: center;
}
.child {
vertical-align: middle;
display: inline-block;
font-size: 12px;
width: 50px;
height: 50px;
background-color: #00f;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
2
3
4
5
6
7
8
9
10
11
12
13
14
# 文本内容居中
text {
height: 100px;
line-height: 100px;
text-align: center;
}
1
2
3
4
5
2
3
4
5