0%

html文本和元素垂直居中

单行文本的垂直居中

类型 属性
水平居中 text-align center
垂直居中 line-height XXpx

示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
#div01 {
width: 100px;
height: 100px;
background-color: skyblue;
text-align: center;
line-height: 100px;
}
</style>
</head>
<body>
<div id="div01">
<span>name</span>
</div>
</body>
</html>

多行文本的垂直居中

使用display:table来实现

属性 说明
display table 使块状元素成为一个块级表格
display table-cell 子元素设置成表格单元格
vertical-align middle 使表格内容居中显示,即可实现垂直居中的效果

示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
#div01 {
width: 100px;
height: 100px;
background-color: skyblue;
text-align: center;
display: table;
}
#div01 span {
display: table-cell;
vertical-align: middle;
}
</style>
</head>
<body>
<div id="div01">
<span>name</span>
</div>
</body>
</html>

元素的垂直居中

1,使用absolute与transform配合实现

步骤:

  • 首先给父级元素添加相对定位position: relative;
  • 然后给子级元素添加绝对定位 position: absolute;(即需要垂直居中的元素)
  • 最后让子级距离父级左边和上边分别为left: 50%; top: 50%; transform: translate(-50%, -50%);

示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
#div01 {
width: 100px;
height: 100px;
background-color: skyblue;
position: relative;
}
#div02 {
width: 30px;
height: 30px;
background-color: red;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
</style>
</head>
<body>
<div id="div01">
<div id="div02"></div>
</div>
</body>
</html>

2,使用flex实现

属性 说明
display flex 弹性容器
justify-content center 定义了项目在主轴上的对齐方式,水平对齐居中
align-items center 定义项目在交叉轴(纵轴)上如何对齐,垂直对齐居中

示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
#div01 {
width: 100px;
height: 100px;
background-color: skyblue;
display: flex;
justify-content: center;
align-items: center;
}
#div02 {
width: 30px;
height: 30px;
background-color: red;
}
</style>
</head>
<body>
<div id="div01">
<div id="div02"></div>
</div>
</body>
</html>