css實現水平垂直居中

純CSS實現水平垂直居中

最近的幾場面試都問了這個問題,本身也只答了2種,感受面試官不滿意,特意總結了幾種在開發中比較實用的方法,與你們分享。css

1、須要知道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,因此沒法用百分比。html

2、不須要知道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自動計算實現web

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~~flex

謝謝

相關文章
相關標籤/搜索