div元素垂直水平居中

image-20220509055101090

垂直居中

line-hight

适用:单行文本垂直居中

1
2
3
4
5
6
7
8
9
<style>
.child {
line-hight: 200px;
}
</style>

<div class="parent">
<div class="child">Text</div>
</div>

垂直居中一张图片

1
2
3
4
5
6
7
8
9
10
11
12
<style>
.parent {
line-hight: 200px;
}
.child {
vertical-align: middle;
}
</style>

<div class="parent">
<img class="child" src="image.png" />
</div>

table

适用:通用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<style>
.parent {
display: table;
}
.child {
display: table-cell;
vertical-align: middle;
}

/* 低版本IE fix bug */
.child {
display: inline-block;
}
</style>

<div class="parent">
<div class="child">Content</div>
</div>

绝对定位和负外边距

适用:块级元素

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<style>
.parent {
position: relative;
height: 200px;
}
.child {
position: absolute;
top: 50%;
left: 0;
height: 100px;
line-height: 100px;
margin-top: -50px;
}
</style>

<div class="parent">
<div class="child">Content</div>
</div>

绝对定位和垂直拉伸

适用:通用,但IE<7版本时不能正常渲染

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<style>
.parent {
position: relative;
width: 100%;
height: 200px;
}
.child {
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
height: 100px;
line-height: 100px;
margin: auto 0;
}
</style>

<div class="parent">
<div class="child">Content</div>
</div>

内边距相等

适用:通用

1
2
3
4
5
6
7
8
9
10
11
12
<style>
.parent {
padding: 5% 0;
}
.child {
padding: 10% 0;
}
</style>

<div class="parent">
<div class="child">Content</div>
</div>

float

适用:通用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<style>
.parent {
height: 200px;
}
.floater {
float: left;
height: 50%;
width: 100%;
margin-bottom: -50px;
}
.child {
clear: both;
height: 100px;
line-height: 100px;
}
</style>

<div class="parent">
<div class="floater"></div>
<div class="child">Content</div>
</div>

水平居中

text-align

适用:文本

1
2
3
4
5
6
7
8
9
10
11
12
13
<style>
.parent {
height: 200px;
text-align: center; /* 继承样式 */
}
.child {
height: 100px;
}
</style>

<div class="parent">
<div class="child">Content</div>
</div>

margin

适用:块级元素

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<style>
.parent {
width: 100%;
height: 200px;
}
.child {
width: 50%;
height: 100px;
margin: 0 auto;
text-align: center;
}
</style>

<div class="parent">
<div class="child">Content</div>
</div>

padding

适用:通用

1
2
3
4
5
6
7
8
9
10
<style>
.child {
padding: 0 5%;
text-align: center;
}
</style>

<div class="parent">
<div class="child">Content</div>
</div>

绝对定位搭配

参考垂直居中绝对定位调试,这里不做赘述。

垂直水平居中

结合垂直居中和水平居中,这里不做赘述。

以下方法也可达到垂直水平居中效果:
1、绝对定位结合 css3 2D 转换方法 translate(x,y) 负值;
2、flex