標籤: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>