1.定位+margin外边距:
父级相对定位,子级绝对定位+左和上外边距为子盒子的一半
.father {
width: 400px;
height: 400px;
background-color: pink;
margin: 100px auto;
position: relative;
}.father .son {
position: absolute;
margin-left: 100px;
margin-top: 100px;
width: 200px;
height: 200px;
background-color: plum;
}
2.定位+transfrom
父级相对定位,子级绝对定位+位移(x,y轴都移动子盒子自身的一半)
.father {
width: 400px;
height: 400px;
background-color: pink;
margin: 100px auto;
position: relative;
}.father .son {
position: absolute;
transform: translate(100px,100px);
width: 200px;
height: 200px;
background-color: plum;
}
3.定位+方位名词
父级相对定位,子级绝对定位+位移(x,y轴都移动子盒子自身的一半)
这里移动子盒子自身距离的一半都用50%来表示,实际是对盒子居中方式---定位+transfrom的优化
.father {
width: 400px;
height: 400px;
background-color: pink;
margin: 100px auto;
position: relative;
}.father .son {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,50%);
width: 200px;
height: 200px;
background-color: plum;
}
4.定位+margin : auto
.father {
width: 400px;
height: 400px;
border: 1px solid #000;
position: relative;
}
.father .son {
width: 200px;
height: 200px;
border: 1px solid #999;
position: absolute;
margin: auto;
top: 0;
left: 0;
right: 0;
bottom: 0;
}
5.flex布局
父级添加flex布局,并且添加x,y轴居中对齐方式 (只用操作父级 不用考虑子级 轻松搞定)
.father {
width: 400px;
height: 400px;
background-color: pink;
margin: 100px auto;
display: flex;
justify-content: center;
align-items: center;
}.father .son {
width: 200px;
height: 200px;
background-color: plum;
}
6.利用display:table-cell
.father {
width: 400px;
height: 400px;
border: 1px solid #000;
display: table-cell;
vertical-align: middle;
text-align: center;
}
.father .son {
width: 200px;
height: 200px;
border: 1px solid #999;
display: inline-block;
}