在前端布局过程中,我们实现水平居中比较简单,一般通过margin:0 auto;和父元素 text-align: center;就能实现。但要实现垂直居中就没有那么容易,下面向大家分享下我工作中实现垂直居中的几种方法。

1、line-height等于hieght/只设line-height

这种方法比较适合文字的居中,其核心是设置行高(line-height)等于包裹他的盒子的高,或者不设高度只设行高,这种适合文字居中且高度固定的场景,使用起来比较方便也比较有用。

//html
  

   555 
 
 
 
//css
.middle{
height: 50px;
line-height: 50px;
background: red;
}

复制代码

html5 文本垂直居中 html文字垂直居中代码_css

值得注意的是如果是行内元素,因为其没有高度,需先把行内元素转换为行内块或者块元素。

2、vertical-align: middle

这种实现元素的居中需要配合父元素设有等于自身高度的行高,且此元素是行内块元素。

只有三个条件都具备,才能实现垂直居中。代码如下:

//html
//css
.main {
width: 200px;
height: 300px;
line-height: 300px;
background: #dddddd;
}
.middle{
background: red;
width: 200px;
height: 50px;
display: inline-block;//或者display: inline-table;
vertical-align: middle;
}

复制代码

html5 文本垂直居中 html文字垂直居中代码_html5 文本垂直居中_02

需要注意的是这种方法需要一个固定的行高,且实现的居中其实是近似居中,并不是真正意义的居中。

3、绝对定位加负外边距

这种方法核心在于先设置需要居中的元素为绝对定位,在设置其top:50%; 加上 margin-top等于负的自身高度的一半来实现居中。好处是实现起来比较方便,且父元素的高度可以为百分比,也不用设行高。代码如下:

//html
//css
.main {
width: 60px;
height: 10%;
background: #dddddd;
position: relative;//父元素设为相对定位
}
.middle{
position: absolute;//设为绝对定位
top: 50%;//top值为50%
margin-top: -25%;//设margin-top为元素高度的一半
width: 60px;
height: 50%;
background: red;
}

复制代码

html5 文本垂直居中 html文字垂直居中代码_html divh垂直居中_03

4、绝对定位加margin:auto

先上代码:

//html
//css
.main {
width: 60px;
height: 10%;
background: #dddddd;
position: relative;//父元素设为相对定位
}
.middle{
width: 30%;
height: 50%;
position: absolute;//设为绝对定位
top: 0;
bottom: 0;//top、bottom设0即可,
left: 0;//如果left、right也设为0则可实现水平垂直都居中
right: 0;
margin:auto;
background: red;
}

复制代码

这种方法好处是不止可以实现垂直居中,还可以实现水平居中,坏处是在网络或性能不好的情况下会有盒子不直接定到位的情况,造成用户体验不好。

5、flex布局

flex布局可以很方便的实现垂直与水平居中,好处很多,在移动端使用比较广泛,坏处就是浏览器兼容性不好。代码如下:

//html
//css
.main {
width: 60px;
height: 10%;
background: #dddddd;
display: flex;//设为flex
justify-content: center;//水平居中
align-items: center;//垂直居中
}
.middle{
width: 30%;
height: 50%;
background: red;
}

复制代码

html5 文本垂直居中 html文字垂直居中代码_css_04