CSS

用最少的代码实现垂直居中

Posted by YorkWong on May 10, 2022

如何用最少的代码实现垂直居中呢?

不多说,上代码

基础html代码结构

1
2
3
<div class="box">        
    <div class="a"></div>    
</div>

方法一:flex布局

1
2
3
4
5
6
7
8
9
10
11
12
13
14
.box{            
    width: 300px;            
    height: 300px;           
    background-color: #ccc;            
    display: flex;            
    display: -webkit-flex;            
    justify-content: center;            
    align-items: center;        
}        
.box .a{            
    width: 100px;            
    height: 100px;            
    background-color: blue;        
}    

方法二:position (元素已知宽度)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
 .box{            
        width: 300px;            
        height: 300px;            
        background-color: red;            
        position: relative;       
    }        
    .box .a{            
        width: 100px;            
        height: 100px;            
        background-color: blue;           
        position: absolute;         
        left: 50%;            
        top: 50%;            
        margin: -50px 0 0 -50px;      
    } 

方法三:osition transform (元素未知宽度)

1
2
3
4
5
6
7
8
9
10
11
12
13
 .box{            
        width: 300px;            
        height: 300px;            
        background-color: red;            
        position: relative;        
    }        
    .box .a{            
        background-color: blue;            
        position: absolute;            
        top: 50%;            
        left: 50%;            
        transform: translate(-50%, -50%);        
    }