To prepare, assume the following HTML

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

Copy the code

The width and height need to be set

1. The position + negative margin

.wrapper{
    position:relative;
}

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

Copy the code

2. position + margin:auto

.wrapper{
    position:relative;
}

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

3.position + calc()

.wrapper{
    position:relative;
}

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

There is no need to set width and height

1.position + transform

.wrapper{
    position:relative;
}

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

2. The flex layout

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