html代码如下:
//html
<div class="parent">
<div class="child"></div>
</div>
一 、脱离文档流的居中
1、margin: auto居中
.parent{
width: 900px;
height: 400px;
background: red;
position: relative;
}
.child{
width: 50%;
height: 50%;
background: blue;
position: absolute;
margin: auto;
left: 0;
top: 0;
right: 0;
bottom: 0;
}
2、负margin居中
.parent{
width: 900px;
height: 400px;
background: red;
position: relative;
}
.child{
width: 400px;
height: 300px;
background: blue;
position: absolute;
left: 50%;
top: 50%;
margin-left: -200px;
margin-top: -150px;
}
二、未脱离文档流的水平垂直居中
1、display:table-cell居中
.parent{
width: 900px;
height: 400px;
background: red;
display: table-cell;
vertical-align: middle;
}
.child{
width: 50%;
height: 50%;
background: blue;
margin: 0 auto;
}
2、flex居中
.parent{
width: 900px;
height: 400px;
background: red;
display: flex;
display: -webkit-flex;
align-items: center; //控制垂直方向居中
-webkit-align-items: center;
justify-content: center; //控制水平方向居中
-webkit-justify-content: center;
}
.child{
width: 50%;
height: 50%;
background: blue;
}
ok~ 本篇圆满完结~