盒子居中

Wenn 于 2022-09-19 发布

已知宽高

<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;  
}
.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;
}
.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); /*只需要减掉盒子本身的一半即可*/
}

盒子宽高未知

.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%)
}
.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; /*继承父盒子*/
}
.box {
    display : flex;
    justify-content : center;
    align-items : center;
    width: 200px;
    height : 200px;
}
.box {
    width : 200px;
    height : 200px;
    border : 1px solid #000;
    display : flex;
}
.son {
    margin : auto;
}
.box {
    display : grid;
    justify-content : center;
    align-items : center;
}
.box {
    width : 200px;
    height : 200px;
    border : 1px solid #000;
    display : grid;
}
.son {
    justify-self : center;
    align-self : center;
}