純CSS實現水平垂直居中
最近的幾場面試都問了這個問題,自己也只答了2種,感覺面試官不滿意,特地總結了幾種在開發中比較實用的方法,與大家分享。
一、需要知道width,height的方案
1.絕對定位 + 負外邊距
<style type="text/css">
.warp{ position: relative; }
.box {
width: 200px;
height: 100px;
position: absolute;
top: 50%; left: 50%;
padding: 0;
margin-left: -100px; /* (width + padding)/2 */
margin-top: -50px; /* (height + padding)/2 */
}
</style>
<div class="warp">
<div class="box">
</div>
</div>
因爲margin/padding的百分比值是參照父元素的width,所以無法用百分比。
二、不需要知道width,height方案
1.絕對定位 + margin:auto
<style type="text/css">
.warp{ position: relative; }
.box {
width: 200px;
height: 100px;
position: absolute;
padding: 0;
margin: auto;
left: 0;
right: 0;
top: 0;
bottom: 0;
}
</style>
<div class="warp">
<div class="box">
</div>
</div>
利用margin:auto自動計算實現
2.絕對定位 + transform
<style type="text/css">
.warp{ position: relative; }
.box {
width: 200px;
height: 100px;
position: absolute;
top: 50%; left: 50%;
-webkit-transform: translate(-50%, -50%);
-ms-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
}
</style>
<div class="warp">
<div class="box">
</div>
</div>
利用translate的百分比是相對本元素寬/高這一特點實現
3.flex
<style type="text/css">
.warp{
display: -webkit-flex;
display: -moz-box;
display: -ms-flexbox;
display: -webkit-box;
display: flex;
-webkit-box-align: center;
-moz-box-align: center;
-ms-flex-align: center;
-webkit-align-items: center;
align-items: center;
-webkit-box-pack: center;
-moz-box-pack: center;
-ms-flex-pack: center;
-webkit-justify-content: center;
justify-content: center;
}
.box {
width: 200px;
height: 100px;
}
</style>
<div class="warp">
<div class="box">
</div>
</div>
其他
除此之外還有table-cell佈局,inline-block佈局等,由於在項目中很少用到,而且感覺table佈局坑太多,就不做描述,有興趣請自行查找。
本文如有錯誤,請在評論區提出。
最後,四月求個offer~~