水平垂直居中的实现方法总结

188 阅读1分钟

1.相对定位+负margin

核心思想就是让子元素先left和top50%使其左上角水平垂直居中

再利-margin-top -margin-left使其的向左上角的方向移动半个宽和高的距离

但是这个方法必须考虑宽高,必须有实际的宽和高

<div class="parent">        
<di class = "box">            
水平垂直居中        
</di>    
</div>   

.parent{
       position: relative;
        width: 100px; 
        height: 100px;
        background-color: aqua; 
       }
.box{
     width: 50px;
     height: 50px;
     position: absolute;//绝对定位           
     left: 50%;//这两个50%是为了让box这个子div的上和左那个角水平垂直居中            
     top: 50%;            
     margin-left: -25px;//为了让整个元素水平垂直居中还要让lefttop向上移动半个宽和高    
     margin-top:-25px;//所以这里用到负marigin的值            
     background-color: blueviolet;        
}

2.绝对定位+margin:auto

核心思想使用left, top,bottom,right都设置为0,让他绝对定位到页面上,

可以不考虑宽和高,但是这个盒子必须要设置实际的宽和高

.box{ 
     width: 50px;
     height: 50px;
     position: absolute;
     left:0;            
     top:0;            
     right: 0;            
     bottom: 0;            
     margin:auto;            
     background-color: blueviolet;  
}

3.绝对定位+transform

使用css3的新特性transform里面有个translate(-50%,-50%)让他向上和向左移动半个宽高,这个方案可以不设置宽高,但是有个问题就是不兼容

.box{            
    position: absolute;            
    left: 50%;            
    top: 50%;            
    transform: translate(-50%,-50%);            
    background-color: blueviolet;
}

4.flex布局也有兼容的问题

  .parent{            
    display: flex;            
    height: 100px;            
    justify-content: center;            
    align-items: center;            
    background-color: blueviolet;        
}
.box{         
     background-color: aqua;    
 }