一:绝对定位+left,top,right,bottom 0+margin:auto
div绝对定位水平垂直居中【margin:auto实现绝对定位元素的居中】,
兼容性:,IE7及之前版本不支持
width: 200px;
height: 200px;
background: green;
position: absolute;
left: 0;
top: 0;
bottom: 0;
right: 0;
margin: auto;
}
二:绝对定位+margin-left和margin-top为负宽高/2
div绝对定位水平垂直居中【margin 负间距】 这或许是当前最流行的使用方法。
div {
width: 200px;
height: 200px;
background: green;
position: absolute;
left: 50%;
top: 50%;
margin-left: -100px;
margin-top: -100px;
}
三: div绝对定位水平垂直居中【Transforms 变形】
兼容性:IE8不支持;
div {width: 200px;
height: 200px;
background: green;
position: absolute;
left: 50%;
/* 定位父级的50% */
top: 50%;
transform: translate(-50%,-50%);
/*自己的50% */
}
四: flex布局
css不定宽高水平垂直居中
.box {height: 600px;
display: flex;
justify-content: center;
align-items: center;
/* 只要三句就可以实现不定宽高水平垂直居中。 */
}
五:父元素table-cell
将父盒子设置为table-cell元素,可以使用text-align:center和vertical-align:middle实现水平、垂直居中。比较完美的解决方案是利用三层结构模拟父子结构
<p class="outerBox tableCell"> </p>
<p class="ok"> </p>
<p class="innerBox">tableCell</p>
<p></p>
<p></p> /* table-cell实现居中 将父盒子设置为table-cell元素,
设置 text-align:center,vertical-align: middle; 子盒子设置为inline-block元素 */
.tableCell {
display: table;}
.tableCell .ok {
display: table-cell;
text-align: center;
vertical-align: middle;
}
.tableCell .innerBox {
display: inline-block;
}