1.父级相对定位,子级绝对定位
.parent{
width: 500px;
height: 500px;
background: #f00;
position: relative;
}
.child{
width: 300px;
height: 300px;
background: #fff;
position: absolute;
top:50%;
left: 50%;
margin-left: -150px;
margin-top: -150px;
}
2.元素宽度未知,
如果元素未知宽度,只需将上面例子中的margin-left: -150px;margin-top:-150px;替换为:transform: translate(-50%,-50%);
.parent{
width: 500px;
height: 500px;
background: #f00;
position: relative;
}
.child{
width: 300px;
height: 300px;
background: #fff;
position: absolute;
top:50%;
left: 50%;
transform: translate(-50%,-50%);
}
3.父级相对定位,子级绝对定位+margin:auto
.parent{
width: 500px;
height: 500px;
background: #f00;
position: relative;
}
.child{
width: 300px;
height: 300px;
background: #fff;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
}
4.flex布局
.parent{
width: 500px;
height: 500px;
background: #f00;
display: flex;
justify-content: center;
align-items: center
}
.child{
width: 300px;
height: 300px;
background: #fff;
}
5.父级display:flex;子级margin:auto
.parent{
width: 500px;
height: 500px;
background: #f00;
display: flex;
}
.child{
width: 300px;
height: 300px;
background: #fff;
margin: auto;
}