前置:html结构如下
<div class="container">
<div class="child"></div>
</div>
1. flex布局
.container{
width: 200px;
height: 200px;
border: 1px solid red;
display: flex;
justify-content: center;
align-items: center;
}
.child{
width: 100px;
height: 100px;
background: black;
}
2. 父元素relative, 子元素absolute + margin负值
.container{
width: 200px;
height: 200px;
border: 1px solid red;
position: relative;
}
.child{
width: 100px;
height: 100px;
background: black;
position: absolute;
left: 50%;
top: 50%;
margin-left:-50px;
margin-top:-50px;
}
3. 父元素relative,子元素absolute并且各个方向为0+margin auto
.container{
width: 200px;
height: 200px;
border: 1px solid red;
position: relative;
}
.child{
width: 100px;
height: 100px;
background: black;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
}
4. 父元素relative,子元素absolute+calc计算偏移量,不用margin
.container{
width: 200px;
height: 200px;
border: 1px solid red;
position: relative;
}
.child{
width: 100px;
height: 100px;
background: black;
position: absolute;
top: calc(50% - 50px);
left: calc(50% - 50px);
}
5. 父元素relative,子元素absolute+ transform
.container{
width: 200px;
height: 200px;
border: 1px solid red;
position: relative;
}
.child{
width: 100px;
height: 100px;
background: black;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
6. grid布局
.container{
width: 200px;
height: 200px;
border: 1px solid red;
display: grid;
}
.child{
width: 100px;
height: 100px;
background: black;
align-self: center;
justify-self: center;
}
总结:
可以看到flex布局,grid布局,margin auto布局和translate布局都是不需要明确知道子元素宽高的,其他几种都需要知道。