父盒子使用flex,不需要知道父子盒子宽高。
.parent{
display: flex;
justify-content: center;
align-items: center;
}
.child{
// 无需设置
}
父盒子使用grid,不需要知道父子盒子宽高。
.parent{
display: grid;
place-items: center;
}
.child{
// 无需设置
}
注:place-items是align-items与justify-items的简写。
父盒子使用grid或flex,子盒子设置margin,不需要知道父子盒子宽高。
.parent{
display: grid;
}
.child{
margin: auto;
}
父盒子使用table-cell,virtical-align,text-align,子盒子设置inline-block,不需要知道父子盒子宽高。
.parent{
display: table-cell;
virtical-align: center;
text-align: center;
}
.child{
display: inline-block;
}
父盒子使用relative定位,子盒子绝对定位和transform,不需要知道父子盒子宽高。
.parent{
position: relative;
}
.child{
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
}
父盒子使用relative定位,子盒子绝对定位和margin,不需要知道父子盒子宽高。
.parent{
position: relative;
}
.child{
margin: auto;
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
}
手动设置子盒子的margin,需要知道父子盒子宽高。
.parent{
height: 300px;
width:200px;
}
.child{
width: 50%;
margin: 50px 25%;
height: 50%;
}