在写页面的时候经常会用到水平和垂直居中,实现有很多种方法,下面将为大家一一介绍。

1、text-align + line-height实现单行文本水平垂直居中(要设置宽度)

html
  • html
1
2
3
4
5
6
7
8
<style>
.test{
text-align: center;
line-height: 100px;
}
</style>


<div class="test" style="background-color: lightblue;width: 200px;">测试文字</div>

2、用定位来实现

将left和top都设置为50%,然后将margin-left和margin-top设置成宽高的负1/2。

css
  • css
1
2
3
4
5
6
7
8
9
div.box{
width: 200px;
height: 400px;
position: absolute;
left: 50%;
top: 50%;
margin-left: -100px;
margin-top: -200px;
}

*兼容性好;
缺点:必须知道元素的宽高.

3、margin:auto

先把元素变成定位元素,再设置元素的定位位置,距离上、下、左、右都为0,最后设置元素的margin样式值为 auto。

css
  • css
1
2
3
4
5
6
7
8
9
10
div.box{
width: 200px;
height: 400px;
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
margin: auto;
}

4、margin + vertical-align

要想在父元素中设置vertical-align,须设置为table-cell元素;
要想让margin:0 auto实现水平居中的块元素内容撑开宽度,须设置为table元素。
而table元素是可以嵌套在tabel-cell元素里面的,就像一个单元格里可以嵌套一个表格

[注意] 若兼容IE7-浏览器,需将结构改为table

html
  • html
1
2
3
4
5
6
7
8
9
10
11
12
13
<style>
.parent{
display:table-cell;
vertical-align: middle;
}
.child{
display: table;
margin: 0 auto;
}
</style>


<div class="parent" style="background-color: lightgray; width:200px; height:100px; ">
<div class="child" style="background-color: lightblue;">测试文字</div></div>

5、 使用flex

  [注意] IE9-浏览器不支持

【1】在伸缩项目上使用margin:auto
html
  • html
1
2
3
4
5
6
7
8
9
10
11
<style>
.parent{
display: flex;
}
.child{
margin: auto;
}
</style>


<div class="parent" style="background-color: lightgray; width:200px; height:100px; ">
<div class="child" style="background-color: lightblue;">测试文字</div></div>
【2】在伸缩容器上使用主轴对齐justify-content和侧轴对齐align-items
html
  • html
1
2
3
4
5
6
7
8
9
10
<style>
.parent{
display: flex;
justify-content: center;
align-items: center;
}
</style>


<div class="parent" style="background-color: lightgray; width:200px; height:100px; ">
<div class="child" style="background-color: lightblue;">测试文字</div></div>

6、使用translate

使用translate时,如果知道宽高就可以直接写宽高的负1/2;如果不知道宽高可以直接写-50%,其实也是高宽的1/2的意思,所以建议大家最好用-50%。

css
  • css
1
2
3
4
5
6
7
8
9
.child{
width: 200px;
height: 200px;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-100px,-100px);
-webkit-transform: translate(-50%,-50%);
}