CSS实现水平垂直居中的几种方式

459 阅读1分钟

准备工作,假设有如下html

<div class="wrapper">
    <div class="box">
        
    </div>
</div>

需要设置宽高

1.position + 负margin

.wrapper{
    position:relative;
}

.box{
    width:100px;
    height:100px;
    position:absolute;
    left:50%;
    top:50%;
    margin-left: -50px;
    margin-top: -50px;
}

2. position + margin:auto

.wrapper{
    position:relative;
}

.box{
    width:100px;
    height:100px;
    position:absolute;
    left:0
    top:0;
    right:0;
    bottom:0;
    margin:auto;
}

3.position + calc()

.wrapper{
    position:relative;
}

.box{
    width:100px;
    height:100px;
    position:absolute;
    left:calc(50% - 50px) ;
    top:calc(50% - 50px) ;
}

不需要设置宽高

1.position + transform

.wrapper{
    position:relative;
}

.box{
    width:100px;
    height:100px;
    position:absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%); 
}

2.flex布局

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