實現div居中的幾種方法

方法一、使用display:table-cell

樣式

<style>
.wrapperbox{border:1px solid red; width:100px; height:100px; display:table-cell; font-size:0; text-align:center; vertical-align:middle; *position:relative;padding:0; overflow:hidden; } 
.innerbox{text-align:center; vertical-align:middle; width:100px\9; *width:auto;font-size:0; *position:absolute;*top:50%;*left:50%;}
 img{ max-height:100px; max-width:100px; *position:relative;*bottom:50%;*right:50%;margin:0 auto;}
</style>

html

<div class="wrapperbox"> 
  <div class="innerbox"> 
     <img src="demo.png" />
  </div>
</div>

此方法div包括層過多;
兼容性:除IE 10及以下不兼容外,谷歌、360、火狐親測兼容

方法二、使用絕對定位實現居中

樣式

<style type="text/css">  
.content {  
    background: #dedede;  
    width:500px;
    height:500px;
    position:relative;
    }  
.content div{
    background: red;
    width:300px;
    height:300px;
    position:absolute;
    top:50%;
    left:50%;
    transform:translate(-50%,-50%); 
}
</style> 

html

    <div class="content">
      <div>test</div>
    </div> 

兼容性:IE 8以上兼容、谷歌、360、火狐親測兼容

方法三、使用絕對定位實現全屏居中

樣式

    <style>
        body{
            margin:0px;
            width:100%;
            height:100%;
        }
        .box{
            position:absolute;
            top:50%;
            left:50%;
            width:500px;
            height:200px;
        }
        .content{
            position:relative;
            top:-50%;
            left:-50%;
            width:100%;
            height:100%;
            background:red;
        }
    </style>

html

    <div class="box">
        <div class="content">
        </div>
    </div>

兼容性:全部兼容

方法四、使用display:flex

樣式

    <style>
    /*居中div的父級*/
.parent{display:flex;justify-content:center;align-items:center;}
    </style>

兼容性:IE10及IE10以上、谷歌、360、火狐親測兼容

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章