水平垂直居中
宽高固定
<div class="parent">
<div class="child"></div>
</div>
1
2
3
2
3
.parent {
height:200px;
background-color: #dcdbdb;
position: relative;
}
.parent .child {
height: 100px;
width: 100px;
background-color: #3eaf7c;
position: absolute;
left: 50%;
top:50%;
margin-left:-50px;
margin-top: -50px;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
2
3
4
5
6
7
8
9
10
11
12
13
14
15
利用 Margin
<div class="parent">
<div class="child"></div>
</div>
1
2
3
2
3
.parent {
height:200px;
background-color: #dcdbdb;
position: relative;
}
.parent .child {
height: 100px;
width: 100px;
background-color: #3eaf7c;
position: absolute;
left: 0;
right:0;
top:0;
bottom:0;
margin:auto;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
Table
<div class="parent">
<div class="child">
<div class="content"></div>
</div>
</div>
1
2
3
4
5
2
3
4
5
.parent {
width: 100%;
height:200px;
background-color: #dcdbdb;
position: relative;
display: table;
}
.parent .child {
display: table-cell;
vertical-align: middle;
}
.parent .child .content {
height: 100px;
width: 100px;
background-color: #3eaf7c;
margin: 0 auto;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
宽高不固定
宽高由内容决定
<div class="parent">
<div class="child"></div>
</div>
1
2
3
2
3
.parent {
height:200px;
background-color: #dcdbdb;
position: relative;
}
.parent .child {
padding: 30px;
background-color: #3eaf7c;
position: absolute;
left: 50%;
top:50%;
transform:translate(-50%,-50%);
}
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
Flex
宽高由内容决定
<div class="parent">
<div class="child">宽高由内容决定</div>
</div>
1
2
3
2
3
.parent {
height:200px;
background-color: #dcdbdb;
display: flex;
justify-content: center;
align-items: center;
}
.parent .child {
padding: 30px;
background-color: #3eaf7c;
}
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
文字居中
这是一段文字
<div class="parent">
<p class="child">这是一段文字</p>
</div>
1
2
3
2
3
.parent {
height:200px;
background-color: #dcdbdb;
}
.parent .child {
text-align: center;
line-height: 200px;
color: #3eaf7c;
}
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9