Six common methods of CSS box centering
<div class="wrapper">
<div class="box"></div>
</div>
------------------------------------- The most traditional method
.wrapper{
position: relative;
width: 400px;
height: 400px;
background-color: aqua;
}
.box{
position: absolute;
width: 100px;
height: 100px;
background-color: red;
left: 50%;
top:50%;
margin-left: -50px;
margin-top: -50px;
}
----------------------------------------Using transform
.wrapper{
position: relative;
width: 400px;
height: 400px;
background-color: aqua;
}
.box{
position: absolute;
width: 100px;
height: 100px;
background-color: red;
left: 50%;
top:50%;
transform: translate(-50%,-50%);
}
-------------------------------------Use flex (elastic layout)
.wrapper{
display: flex;
width: 400px;
height: 400px;
background-color: aqua;
justify-content: center;
align-items: center;
}
.box{
width: 100px;
height: 100px;
background-color: red;
}
---------------------------------Use justify-content: space-around; (rarely used)
.wrapper{
display: flex;
width: 400px;
height: 400px;
background-color: aqua;
/*justify-content: space-between; (左右两边对齐)*/
justify-content: space-around;
align-items: center;
}
.box{
width: 100px;
height: 100px;
background-color: red;
}
------------------------------------ Expand
justify-content: center; Horizontally center
justify-content: space-between; Justify-content: space- around
; The distance around the box is equal (can be used to center)
justify-content: flex-start; Left
justify-content: flex-end; Right justify
--------------------------------- new learner
.wrapper{
display: flex;
width: 200px;
height: 400px;
background-color: aqua;
position: relative;
}
.box{
width: 100px;
height: 100px;
background-color: red;
position: absolute;
margin: auto;
top: 0;
left: 0;
right: 0;
bottom: 0;
}
---------------------------------利用display: table-cell; vertical-align: middle;
.wrapper{
display: flex;
width: 400px;
height: 400px;
background-color: aqua;
display: table-cell;
vertical-align: middle;
}
.box{
width: 100px;
height: 100px;
background-color: red;
margin: auto;
}