随便举个例子
<div class="father">
<div class="son"></div>
</div>
情况一:父盒子与子盒子宽度固定不变,这种直接不讨论
父盒子与自盒子宽度不固定
flex布局
我平常最常用的方法,简单方便
.father{
border: 1px solid red;
width: 400px;
height: 400px;
display: flex;
justify-content: center;
align-items: center;
}
.son{
width: 200px;
height: 200px;
border: solid 1px blue;
}
transform
平常也用到过
.father {
border: 1px solid red;
width: 600px;
height: 600px;
position: relative;
}
.son {
width: 200px;
height: 200px;
border: solid 1px blue;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
绝对定位
这种方法是我平常很少用的,在这记录一下
.father{
border: 1px solid red;
width: 400px;
height: 400px;
position: relative;
}
.son{
width: 200px;
height: 200px;
border: solid 1px blue;
margin: auto;
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
}