網(wǎng)上這種類型的文章數(shù)之不盡,作為個(gè)人學(xué)習(xí)的一個(gè)整理,僅供參考,歡迎斧正。
兼容性方面請(qǐng)參考http://caniuse.com/
方法一:table-cell實(shí)現(xiàn)垂直居中
缺點(diǎn):margin無效(我給所有元素設(shè)置了margin:auto的)
優(yōu)點(diǎn):兼容IE8以上瀏覽器,動(dòng)態(tài)設(shè)置居中,不需要知道寬高
//html
<div class="ct1 ct">
<div class="box1 box"></div>
</div>
//css
.ct {
width: 300px;
height: 300px;
border: 1px solid red;
margin: 0 auto;
}
.box {
width: 80px;
height: 80px;
background: lightblue;
}
.ct1 {
display: table-cell;
vertical-align: middle;
text-align: center;
}
.box1 {
display: inline-block;//為了使text-align生效
}
效果:

image.png
方法二:父元素設(shè)置相對(duì)定位,子元素絕對(duì)定位。
缺點(diǎn):
1、要么必須知道寬高,手動(dòng)設(shè)置偏移量(margin量)。要么用css3的tranform(IE11以上,兼容性不好)
2、子元素高于父元素會(huì)超出父元素直接顯示,不會(huì)出現(xiàn)滾動(dòng)條
優(yōu)點(diǎn):
影響小,寫法固定且簡便
//html
<div class="ct2 ct">
<div class="box2 box"></div>
</div>
//css
.ct {
width: 300px;
height: 300px;
border: 1px solid red;
margin: 0 auto;
}
.box {
width: 80px;
height: 80px;
background: lightblue;
}
.ct2 {
position: relative;
}
.box2 {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
效果:

image.png
方法三:display:flex
缺點(diǎn):對(duì)IE兼容性不好,IE11才部分支持
優(yōu)點(diǎn):用起來又簡單又方便,很爽啊有木有~~(?′▽`)??
//html
<div class="ct3 ct">
<div class="box3 box"></div>
</div>
//css
.ct {
width: 300px;
height: 300px;
border: 1px solid red;
margin: 0 auto;
}
.box {
width: 80px;
height: 80px;
background: lightblue;
}
.ct3{
display: flex;
align-items: center;
justify-content: center;
}

image.png
方法四:定位+偏移0+margin:auto
//html
<div class="ct4 ct">
<div class="box4 box"></div>
</div>
//css
.ct4{
position: relative;
}
.box4{
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
}

image.png