CSS元素居中

居中

  • 单行文本水平垂直&垂直居中: text-align、line-height, 元素必须有高度
1
2
3
4
5
6
7
8
9
10
11
12
<style>
.single-text {
height: 50px;
line-height: 50px;
background: #000;
color:#ee00ff;
text-align: center;
}
</style>
<div class="single-text">
这里是一个单行文本
</div>
  • 多行文本垂直居中: display: table-cell 、vertical-align: middle;
1
2
3
4
5
6
7
8
9
10
11
12
13
<style>
.mult-text {
width: 400px;
height: 90px;
background: #ee00ff;
color: #000;
display: table-cell;
vertical-align: middle;
}
</style>
<div class="mult-text">
多行文本垂直居中: display: table-cell 、vertical-align: middle;
</div>
  • div 垂直居中: 父元素 display: table-cell; vertical-align: middle;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<style>
.table-parent {
background: #000;
height: 60px;
display: table-cell;
color: #fff;
vertical-align: middle;
}
</style>
<div class="table-parent">
<div class="table">
display: table-cell;
</div>
</div>
  • div水平垂直居中: 父元素relative. 子元素: absolute left right bottom top : 9; margin: auto; 子元素有高度、宽度
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<style>
.relative-parent {
background: #000;
height: 90px;
color: #fff;
position: relative;
}
.position-child {
position: absolute;
height: 50px;
width: 300px;
left: 0;
right: 0;
bottom: 0;
top: 0;
margin: auto;
}
</style>
<div class="relative-parent">
<div class="position-child">
父元素relative. 子元素: absolute;
</div>
</div>
  • 绝对定位&负值, 子元素有宽度、高度
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: 200px;
height: 200px;
background-color: #e0ffee;
}
.child {
position: absolute;
width: 100px;
height: 100px;
top: 50%;
margin-top: -50px;
left: 50%;
margin-left: -50px;
background: #2545c4;
}
</style>
<div class="parent">
<div class="child"></div>
</div>
  • 同上.绝对定位&translate 子元素不需要有宽度、高度
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<style>
.parent-translate {
position: relative;
width: 200px;
height: 200px;
background-color: #e0ffee;
}
.child-translate {
position: absolute;
background: #2545c4;
left: 50%;
top: 50%;
padding: 20px;
transform: translateX(-50%) translateY(-50%);
}
</style>
<div class="parent-translate">
<div class="child-translate">
哈哈这里是一个子元素哦哦哦哦
</div>
</div>
  • div水平垂直居中: 负元素dispaly: flex; juestify-content: center; align-item: center;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<style>
.flex-parent {
background: #2545c4;
height: 90px;
color: #fff;
display: flex;
justify-content: center;
align-items: center;

}
.flex-child {
background-color: #e0ffee;
}
</style>
<div class="flex-parent">
<div class="flex-child">
父元素flex
</div>
</div>