让一个div框针对上级容器,上下左右都居中(水平垂直居中)
1、Position
position :方法1
.parent{
position: relative;
}
.child{
position: absolute;
left:50%;
top:50%;
transform: translate(-50%, -50%);
}
position :方法2
.parent{
position: relative;
}
.child{
width: 200px;
height: 200px;
position: absolute;
left:50%;
top:50%;
margin-left:-100px;
margin-top:-100px;
}
position :方法3
.parent{
position: relative;
}
.child{
width: 200px;
height: 200px;
position: absolute;
left:0;
top: 0;
bottom: 0;
right: 0;
margin: auto;
}
position :方法4(绝对定位:calc() 函数动态计算实现水平垂直居中)
.parent{
position: relative;
height:800px;
width: 400px;
}
.child{
position: absolute;
width: 200px;
height: 50px;
left:calc((400px - 200px)/2);
top:calc((160px - 50px)/2);
}
2、Flex
flex:方法1
.parent{
height:800px;
display:flex;
align-items:center;// 垂直居中
justify-content:center;// 水平居中
}
.child{
width: 200px;
height: 200px;
}
table-cell
table-cell:方法1
.parent{
display: table-cell;
vertical-align: middle;
text-align: center;
width: 240px;
height: 180px;
}
.child{
width: 200px;
height: 200px;
}