css實現水平、垂直居中的幾種方法

  1. 用text-align: center來實現水平居中(只能實現文本的水平居中)css

//html
<div class="center">
    文本水平居中
</div>
//css
.center{width: 200px;height: 100px;background-color: #a036b4;
         text-align: center;  /*水平居中*/
     }

2.用margin:auto實現塊級元素的水平居中html

<div class="center">
   <div class="child_div"></div>
</div>

.center{width: 200px;height: 100px;background-color: #a036b4;

     }
 .child_div{width: 50px;height: 50px;background-color: blue;margin: 0 auto;/*水平居中*/}

3.使用浮動float來實現水平居中,用float:left;left:50%;同時margin-left:自身寬度的一半;瀏覽器

<div class="center">
   <div class="child_div"></div>
</div>

 .center{width: 200px;height: 100px;background-color: #a036b4;margin: 0 auto;}
     .child_div{width:50px;height:50px;background-color:blue;
         float:left;position:relative;left:50%;margin-left: -25px;/*水平居中*/}

4.固然既然浮動能夠實現水平中,那麼絕對定位position:absolute也能實現spa

html代碼同上,只是修改css中的定位,代碼以下
code

 .center{width: 200px;height: 100px;background-color: #a036b4;margin: 0 auto;}
     .child_div{width:50px;height:50px;background-color:blue;
         position: absolute;left: 50%;margin-left: -25px;/*水平居中*/}

5.用display:inline-block,可是僅inline-block屬性是沒法讓元素水平居中,他的關鍵之處要在元素的父容器中設置text-align的屬性爲「center」,這樣才能達到效果,並且存在一些問題:須要額外處理inline-block的瀏覽器兼容性。orm

<div class="center">
    <span class="list"></span>
</div>

  .center{width: 100px;height: 100px;background-color: #a036b4;margin: 0 auto;
            text-align: center;}
     .list{display: inline-block;
        width: 20px; height: 50px; background-color: blue;list-style: none; }

6.用display: table-cell實現水平居中,在父元素中用display: table。htm

7.用<center></center>.it

這三種方法相對前面比較少用,使用相對也複雜些,這裏暫不實現操做。。。io


實現垂直居中的幾種方法:table

  1. 用display: table-cell實現水平居中,在父元素中用display: table,優勢內容能夠動態改變高度。

<div class="center">
   <div class="child_div">content</div>
    <div class="child_div">content</div>
</div>

.center{width: 200px;height: 200px;background-color: #a036b4;display: table; }
     .child_div{display: table-cell;vertical-align:middle;/*垂直居中*/
                width:50px;height:50px;background-color:blue;}

2.用line-height來實現垂直居中,缺點只是在有單個元素時有效。

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

 .child_div{line-height: 100px;/*垂直居中*/
                width:100px;height:100px;background-color:blue;}

3.用絕對定位的方法來實現垂直居中,同水平居中同樣,也要去掉自身的高度的一半,具體代碼實現以下。

<div class="center">
   <div class="child_div">content</div>
</div>

.center{width: 200px;height: 200px;background-color: #a036b4; }
     .child_div{position: absolute;top: 50%;margin-top: -25px;/*垂直居中*/
                width:50px;height:50px;background-color:blue;}

4.用margin:auto;實現垂直居中,實現起來比較簡單。

<div class="center">
   <div class="child_div">content</div>
</div>

 .center{width: 200px;height: 200px;background-color: #a036b4;}
     .child_div{position:absolute;top:0;bottom:0; margin:auto;/*垂直居中*/
                width:100px;height:100px;background-color:blue;}
相關文章
相關標籤/搜索