css中垂直居中几种方式

124 阅读1分钟

 html结构如下:

<div>     
   <div>垂直居中</div>
</div>

方法1:display:flex

.box{
    display: flex;
    justify-content:center;
    align-items:Center;
}

方法2:绝对定位和负边距

.box{position:relative;}
.box div{
    position: absolute;
    width:100px;
    height: 50px;
    top:50%;
    left:50%;
    margin-left:-50px;
    margin-top:-25px;
    text-align: center; 
}

方法3:translate

.box{position:relative;}

.box div{
            position: absolute;
            top:50%;
            left:50%;
            width:100%;
            transform:translate(-50%,-50%);
            text-align: center;
        }

方法4:table-cell

.box{
  display: table-cell;
    vertical-align: middle;
    text-align: center;        
}

方法5:偏移量0+margin:auto

.box{
  positon:relative;
}
.box div{
  positon:absolute;
  top:0;bottom:0;left:0;right:0;
  margin:auto;
}