div塊元素垂直水平居中方法總結


1、已知塊級元素的寬和高,使用絕對定位+外邊距設定水平垂直居中。

父元素position:relative,子元素position:absolute;top:50%;left:50%;margin-top:-height/2;margin-left:-width/2;

效果圖如下

 

代碼:

<div class="box">
    <div class="center-box1">
        <p>【第一種方法】知道長和寬,使用絕對定位+外邊距設定水平垂直居中</p>
    </div>
</div>

.box {
    background: #6c94be;
    width: 100%;
    height: 450px;
    position: relative;  
}
.center-box1 {
    position: absolute;
    top: 50%;
    left: 50%;
    margin-top: -100px;
    margin-left: -100px;
    width: 200px;
    height: 200px;
    background: #5B83AD;
}

2、使用css3樣式屬性display:flex設定水平垂直居中,父元素樣式屬性display:flex;子元素使用margin:auto;未知子元素高度的時候依然可以使用。

一般chrome和火狐都能很好地支持。ie不支持

效果圖如下:

代碼:

<div class="box">    
    <div class="center-box2">
        <p>【第二種方法】使用css3樣式屬性display:flex設定水平垂直居中</p>
    </div>
</div>

.box {
    background: #6c94be;
    width: 100%;
    height: 450px;
    display: flex;
}
.center-box2 {
    margin: auto;
    width: 200px;
    background: #5B83AD;
}

3、依然使用絕對定位+css3樣式屬性transform

transform中translate偏移的百分比值是相對於自身大小的,無論絕對定位元素的尺寸是多少,其都是水平垂直居中顯示的,但問題是兼容性不好。IE9+以及其他現代瀏覽器才支持。IE9之前版本不支持,在IE8模式下,不居中。

效果圖如下:

代碼:

<div class="box">    
    <div class="center-box3">
        <p>【第三種方法】使用css3樣式屬性transform,transform中translate偏移的百分比值是相對於自身大小的</p>
    </div>
</div>

.box {
    background: #6c94be;
    width: 100%;
    height: 450px;
    position: relative;  
}

.center-box3 {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%,-50%);
    background: #5B83AD;
    width: 200px;
}

 4、已知塊級元素的寬和高,設置其樣式屬性position:absolute;top:0;left:0;bottom:0;right:0;+margin:auto;

效果圖如下:

代碼:

<div class="box">    
    <div class="center-box4">
        <p>【第四種方法】已知寬和高,絕對定位+margin:auto;</p>
    </div>
</div>

.box {
    background: #6c94be;
    width: 100%;
    height: 450px;
    position: relative;
}
.center-box4 {
    position: absolute;
    top: 0;
    left: 0;
    bottom: 0;
    right: 0;
    width: 200px;
    height: 200px;
    background: #5B83AD;
    margin: auto;
}

未完待續...

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM