CSS置中實現完整攻略

來源:互聯網
上載者:User

標籤:play   content   使用   cell   table   inline   元素   ddl   lock   

水平置中:

1) 行內元素解決方案

只需要把行內元素包裹在一個屬性display為block的父層元素中,並且把父層元素添加如下屬性即可:text-align: center

適用元素:文字,連結,及其其它inline或者inline-*類型元素(inline-block,inline-table,inline-flex)

2)塊狀元素解決方案

對於塊狀元素(display:block)來說,我們需要將它的左右外邊距(即,margin-left,margin-right)設定為auto,即可實現塊狀元素的置中,如下:

.center{
/* 這裡可以設定頂端外邊距 */
margin: 10px auto;
}

3)多個塊狀元素解決方案

如果頁面裡有多個塊狀元素需要水平排列置中,可以將元素的display屬性設定為inline-block,並且把父元素的text-align屬性設定為center即可實現

4)水平置中:多個塊狀元素解決方案 (使用flexbox布局實現)

使用flexbox布局,只需要把待處理的塊狀元素的父元素添加屬性display:flex及justify-content:center即可

5)垂直置中:單行的行內元素解決方案

當一個行內元素,即inline,inline-*類型的元素需要置中的話,可以將它的height和line-height同時設定為父元素的高度即可實現垂直置中效果。

#container{  background: #222;  height: 200px;}/*  以下代碼中,將a元素的height和line-height設定的和父元素一樣高度即可實現垂直置中 */a{    height: 200px;  line-height:200px;    color: #FFF;}

6)垂直置中:多行的行內元素解決方案

組合使用display:table-cell和vertical-align:middle屬性來定義需要置中的元素的父容器元素產生效果,如下:

.container{  background: #222;  width: 300px;  height: 300px;  /* 以下屬性垂直置中 */  display: table-cell;  vertical-align:middle;}

  

CSS置中實現完整攻略

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.