已知宽高
- 第一种 absolute+margin auto
<div class='.box'>
<div class='.son'></div>
</div>
.box {
width : 400px;
height : 400px;
position : relative;
border : 1px solid #000;
}
.son {
width : 40px;
height : 40px;
background-color : #0ff;
position : absolute;
left:0;
right:0;
top:0;
bottom:0;
margin:auto;
}
- 第二种 absolute + 负margin
.box {
width : 200px;
height : 200px;
border : 1px solid #000;
position : relative;
}
.son {
width : 40px;
height : 40px;
background-color : #0f0;
position : absolute;
left : 50%;
top : 50%;
margin-top : -20px;
margin-left : -20px;
}
- 第三种 absolute+calc
.box {
width : 200px;
height : 200px;
border : 1px solid #000;
position : relative;
}
.son {
width : 40px;
height : 40px;
background-color : #0f0;
position : absolute;
top : calc(50% - 20px); /*需要注意在二者之间保留空格,否则不生效*/
left : calc(50% - 20px); /*只需要减掉盒子本身的一半即可*/
}
盒子宽高未知
- 第一种 absolute+transform
.box {
width : 200px;
height : 200px;
border : 1px solid #000;
position : relative;
}
.son {
width : 40px;
height : 40px;
background-color : #0f0;
position : absolute;
top : 50%;
left : 50%;
transform : translate(-50%,-50%)
}
- 第二种 line-height + vertical-align
.box {
width : 200px;
border : 1px solid #000;
line-height : 200px;
text-align : center;
}
.son {
background-color : #0f0;
display : inline-block;
vertical-align : middle; /*中线对齐*/
line-height : initial; /*继承父盒子*/
}
- 第三种 flex布局
.box {
display : flex;
justify-content : center;
align-items : center;
width: 200px;
height : 200px;
}
- 第四种 flex+margin
.box {
width : 200px;
height : 200px;
border : 1px solid #000;
display : flex;
}
.son {
margin : auto;
}
- 第五种 grid布局
.box {
display : grid;
justify-content : center;
align-items : center;
}
- 第六种 grid
.box {
width : 200px;
height : 200px;
border : 1px solid #000;
display : grid;
}
.son {
justify-self : center;
align-self : center;
}