CSS水平置中

來源:互聯網
上載者:User

標籤:style   blog   class   code   java   tar   

這裡指的水平置中當然是說通過CSS來自動控制的,而不是說計算之後,設定一個位置來指定置中的。

一般情況下有三種實現方式:

在實現方式中,我們定義兩個名詞來方便後面的解說:out--包含需要被置中元素的那個容器,in--需要置中的元素。

1. text-align: center

  • 設定out的text-align: center
  • 保證in的display為inline

2. margin-left : auto; margin-right: auto

  • 設定in的margin-left : auto; margin-right: auto
  • 保證in的display為block

3. 負外邊距方式

  • 設定in的position:absolute
  • 設定in的left:50%
  • 設定in的margin-left: 負的in的寬度的一半(例如in的寬度是100px,那麼設定這裡為-50px)
  • 設定out的position:absolute/relative
  • 需要明確知道in的寬度

三種方式用起來都比較簡單,但是都有自己的適用範圍,上面給出的是達到置中目標而需要的條件,其中標明紅色的地方即是條件,也是方法的局限所在。

 

前兩種的原理都比較好理解,第三種的原理稍微講一下,也很好理解:

實際上主要是兩步,第一把in通過left:50%移動到out的中間,如果in只是一條線,那麼到這裡其實工作已經完成了。但是如果in有寬度的話,那麼就會發現它的做邊框正好位於out的中間位置。ok,

很顯然的,第二步我們要把in再往左移動in寬度的一半,即可讓in的中間位於out的中間,即in居於out的中間。

 

 

下面以in和out都是div來舉例,給出代碼,代碼中包含全部三種方式也可以直接點擊下面的demo地址 http://demo.zhengjiachao.com/css/hori-center.html

<!doctype html><html><head><meta http-equiv="content-type" content="text/html; charset=UTF-8" /><script type="text/javascript" src="../resource/js/jquery-1.7.2.js"></script><style type="text/css">.out{    height:200px;    background-color: orange;    margin : 10px;}.in{    width:100px;    height:100px;    background-color: gray;}.out.type-1{    text-align: center;}.in.type-1{    display: inline;}.in.type-2{    margin : 0 auto;}.out.type-3{    position: relative;}.in.type-3{    position: absolute;    left: 50%;    margin-left: -50px;}</style></head><body><div class="out type-1">    <div class="in type-1">        1 text-align: center    </div></div><div class="out type-2">    <div class="in type-2">        2 margin: 0 auto;    </div></div><div class="out type-3">    <div class="in type-3">        3 負外邊距    </div></div><script type="text/javascript"></script></body></html>

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.