CSS元素垂直居中的几种方法

在网页响应式布局中,实现水平居中很简单。可是,垂直居中方面,元素的宽度和高度是不可控的,所以很多办法并不适用。

总结了下平时用到的垂直居中的几种办法:

demo中HTML代码:

<div class="center">
        <span></span>
 </div>

一:使用table-cell;

CSS代码:

.table{
  display: table;
  width: 100%;
  height: 100%;
}
.center{
  display: table-cell;
  vertical-align:middle;
  text-align: center;
}
span{
  display: block;
  width: 100px;
  height: 100px;
  margin: 0 auto;
  background-color: #cecece;
}

HTML结构:

<div class="table">
      <div class="center">
           <span></span>
      </div>
</div>

从上面代码可以看出,为了实现垂直居中,添加了额外的元素作为外部容器,且同样要设置外部容器的高度,所以一般情况下不采用这种方式。

二:使用absolute定位

CSS代码:

.center{
        position: relative;
        height: 100%;/*必须定义父级元素的高度*/
        text-align: center;
    }
    span{
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        display: block;
        width: 100px;
        height: 100px;
        margin:auto;/*margin为auto而不是margin:0 auto*/
        background-color: #cecece;
    }

三:使用translate

CSS:

.center{
        position: relative;
        height: 100%;/*必须定义父级元素的高度*/
        text-align: center;
    }
    span{
        position: absolute;
        top: 50%;
        left: 50%;
        right: 0;
        bottom: 0;
        display: block;
        width: 100px;
        height: 100px;
        background-color: #cecece;
        transform:translate(-50%,-50%);
        -webkit-transform:translate(-50%,-50%);
    }

四:使用flex布局

CSS:

.center{
        height: 100%;
        display: flex;
        display: -webkit-flex;
        justify-content:center;
        align-items:center;
    }
    span{
        display: block;
        width: 100px;
        height: 100px;
        margin: 0 auto;
        background-color: #cecece;
    }

五:使用calc()

CSS:

.center{
        position: relative;
        height: 100%;
    }
    span{
        position: absolute;
        top: calc(50% - 50px);
        left: calc(50% - 50px);
        display: block;
        width: 100px;
        height: 100px;
        background-color: #cecece;
    }

以上五种垂直居中为在项目中使用到的,以后在使用中,可根据页面布局情况选择最合适的方式。

原文地址:https://www.cnblogs.com/hesuy/p/5629959.html