實現居中的CSS方法
阿新 • • 發佈:2019-02-14
ble show -c 結果 info ont class mar tab
在實際開發過程中,元素居中是常用的布局之一,為此特別整理了幾種居中方式:
一、table-cell
先看看html文檔結構:
<div class="show show1"> <p>1、垂直居中</p> </div>
再看看css樣式,因為例子比較多,基礎樣式都為都為show,後面不再重復了
.show{ width: 200px; height:200px; background: #999; margin: 25px; } .show1{ display: table-cell; vertical-align:middle; text-align: center; }
在瀏覽器中打開我們可以看到:
這邊需要註意:
1、table-cell不感知margin,我在基礎樣式中添加了margin值,在瀏覽器開發工具中看不到margin有值。
2、設置float或position會對默認布局造成破壞,可以考慮為之增加一個父div定義float等屬性。
二、display:flex
html文檔結構幾乎一樣不再重復,直接看css樣式:
.show2{ display:flex; justify-content: center; align-items: center; }
相比第一個例子,這邊的margin值得以體現。
三、絕對定位和負邊距
html文檔結構:
<div class="base show show3"> <p>3、絕對定位和負邊距</p> </div>
css樣式:
.base{ position:relative; } .show3 p{ position:absolute; width:100px; height:50px; top:50%; left:50%; margin-left:-50px; margin-top:-25px; text-align: center; background-color: #007AFF; }
結果如圖所示:
四、絕對定位和0
css樣式:
.show4 p{ position: absolute; width: 50%; height: 50%; overflow:auto; margin:auto; text-align: center; top: 0; left: 0; bottom: 0; right: 0; background-color: #007AFF; }
結果:
實現居中的CSS方法