CSS垂直水平置中,css垂直置中

來源:互聯網
上載者:User

CSS垂直水平置中,css垂直置中

小小的總結一下:行內元素水平置中用text-align: center;區塊層級元素水平置中用margin-left: auto; margin-right: auto;

 

首先討論一下單行時的情況。

毫無疑問,這是最簡單的一種情況。

HTML結構如下:

1 <div class="demo">2     <span>111111111111111111111111111111111111</span>3 </div>

高度不固定(這種方法同樣適用於多行文時的情況,下面就不再討論)

1 .demo {2     text-align: center; 3     padding-top: 20px;4     padding-bottom: 20px;5 }

高度固定

1 .demo {2     text-align: center;3     height: 100px;4     line-height: 100px;5 }

 

接下來,討論下多行時的情況。

HTML結構如下:

1 <div class="demo">2     <span>111111111111111111111111111111111111<br />22222222222222222222</span>3 </div>

高度不固定時只需要添加pading值就可以,不多加討論了。

高度固定時

方法一:父元素設定display: table,子項目設定display:table-cell。利用了表格的特性。

 1 .demo { 2     height: 100px; 3     display: table; 4     margin-left: auto; 5     margin-right: auto; 6 } 7 .demo span { 8     display: table-cell; 9     vertical-align: middle;10 }

方法二:父元素設定position: relative,子項目設定position: absolute。主要是利用了translate的中心是相對於元素本身的特點。

 1 .demo { 2   position: relative; 3   height: 100px; 4 } 5  6 .demo span { 7   position: absolute; 8   left: 50%; 9   top: 50%;10   -webkit-transform: translate(-50%, -50%);11       -ms-transform: translate(-50%, -50%);12           transform: translate(-50%, -50%);13 }

方法三:利用flex布局。

.demo {  height: 100px;  display: -webkit-box;  display: -webkit-flex;  display: -ms-flexbox;  display: flex;  -webkit-box-pack: center;  -webkit-justify-content: center;      -ms-flex-pack: center;          justify-content: center;  -webkit-box-align: center;  -webkit-align-items: center;      -ms-flex-align: center;          align-items: center;}

方法四:利用:after,:before偽類,結合inline-block的特性實現垂直置中。

 1 .demo { 2   height: 100px; 3   text-align: center; 4 } 5  6 .demo:after, .demo:before { 7   display: inline-block; 8   vertical-align: middle; 9   width: 0;10   height: 100%;11   visibility: hidden;12   content: '';13 }14 15 .demo span {16   display: inline-block;17   vertical-align: middle;18 }

 

暫時就想到這些了。

聯繫我們

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