css实现水平垂直居中

css 实现水平垂直居中的n种方法

方式一:

最常用的方法是使用height + line-height的方式,设置同样的值,配合text-align的使用,即可实现文本的水平垂直居中对齐。

1
2
3
4
5
.box{
height: 100px;
line-height: 100px;
text-align: center;
}

缺点:固定高度,无法实现两行文本的垂直居中对齐

方式二:

使用绝对定位的方法,配合margin负值使用。可以实现元素的水平垂直居中效果。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
.box{
width: 100px;
height: 100px;
position: absolute;
top: 50%;
left: 50%;
margin-top: -50px;
margin-left: -50px;
}
/*简化*/
.Box{
width: 100px;
height: 100px;
position: absolute;
top: calc(50% - 50px);
left: calc(50% - 50px);
}

缺点:固定高度,高度无法自适应内容。元素脱离文档流。

方式三:

使用绝对定位的方法,配合margin:auto使用。可以实现元素的水平垂直居中效果。

1
2
3
4
5
6
7
8
.box{
position: absolute;
margin: auto;
top: 0;
right: 0;
bottom: 0;
left: 0;
}

缺点:元素脱离文档流。

方式四:

使用display:table-cell,将父元素的display,变成表格,再配合vertical-align:middle使用。可以实现元素的水平垂直居中效果。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<style>
.box{
display: table;
vertical-align: middle;
}
.obox{
display: table-cell;
vertical-align: middle;
text-align: center;
}
</style>
<body>
<div class='box'>
<div class='obox'></div>
</div>
</body>

缺点:改变了父元素的display,因为IE6-7不支持display:table-cell,所以使用了大量的hack,而且必须有3个元素,不然不能定位。

方式五:

使用display:inline-block,必须给父元素设置高度再配合vertical-align:middle使用。可以实现元素的水平垂直居中效果。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<style>
.box{
height: 100px;
}
.obox{
display: inline-block;
vertical-align: middle;
text-align: center;
}
</style>
<body>
<div class='box'>
<div class='obox'></div>
</div>
</body>

缺点:多了一个标签,需要给父元素设置高度不然没参照物。而又因为IE6-7不支持display:inline-block,增加了hack。

方式六:

CSS3中存在flex布局(伸缩布局盒模型,也叫弹性布局盒模型),对于flex熟悉的朋友来说,使用flex实现水平垂直居中是再简单不过的了。

当我们使父元素display: flex时,margin: auto不仅可以水平居中,也能够实现垂直居中。这是因为auto外边距会平分水平或垂直方向上的额外空间。

当然,也可以使用justify-content: center来定义弹性项目主轴的对齐方式,align-items: center来定义弹性项目侧轴的对齐方式。

1
2
3
4
5
6
7
8
9
10
.box{
display: flex;
align-items: center;
justify-content: center;
}
/*or*/
.Box{
display: flex;
margin: auto;
}

缺点:兼容问题

方式七:

CSS3中还新增了grid布局(网格布局)

1
2
3
4
5
.box{
display: grid;
align-items: center;
justify-content: center;
}

缺点:兼容问题

Tip:

  • 什么是 CSS hack ?

    • 由于不同厂商的浏览器,比如Internet Explorer,Safari,Mozilla Firefox,Chrome等,或者是同一浏览器的不同版本,如IE6和IE7,对CSS的解析认识不完全一样,因此会导致生成的页面效果不一样,得不到所需要的页面效果。 需要针对不同的浏览器去写不同的CSS,让它能够同时兼容不同的浏览器,能在不同的浏览器中也能得到我们想要的页面效果。

    • 1
      2
      3
      div { 
      -webkit-background:green;/*forfirefox*/
      }
  • hack 三大类

    • CSS属性前缀法
    • 选择器前缀法
    • IE条件注释法(即HTML头部引用if IE)Hack