HTML中實現子容器垂直置中的幾種方式

來源:互聯網
上載者:User

標籤:

  年前前端圈蠻熱鬧的,大家撕的挺歡的,阿當想說的並不是固步自封,抵制學習新東西,而是想說要夯實基礎,然後對架構有甄別能力的基礎上再去有選擇的學習。歸根結底還是要掌握好根本,也就是道,其餘的工具都不過是術,得道了,術這些東西自然手到擒來。好了,胡扯打住。阿當說區別真前端和偽前端其中一點就是能說出幾種HTML元素的垂直置中方式。

  那我在這裡總結一下我get的幾種方式。

  代碼結構如下,父容器,子容器寬高不確定。

<div class="parent">    <div class="child"></div></div>

一、實現子容器水平置中的幾種方式:

  1. 子容器.child設定display: inline-block; 父容器設定text-align: center。這種方法相容性好,可以做一下hack處理來實現對IE6,7的相容,子容器 _display: inline; _zoom: 1;

  2. 利用table元素特性。子容器.child{display: table; margin: 0 auto;}。

  3. 利用定位,即.parent{position: relative}; .child{position: absolute; left: 50%; transform: translateX(-50%)}。

這種方法相容性較差,IE9以上支援, IE9需加私人首碼-ms- ( http://caniuse.com/#search=transform )

  4. 利用彈性盒子布局。父容器display: flex; justify-content: center。相容性比較差,IE10,IE11對彈性布局都是部分支援,IE10需加私人首碼。

 

二、實現子容器的垂直置中的幾種方式:

  1. 父容器display: table-cell; vertical-align: middle。

  2. 父容器position: relative; 子容器position: absolute; top: 50%; transform: translateY(-50%);

  3. 父容器,display: flex; align-items: center。

 

綜上,實現子容器水平、垂直置中對齊的方式有(父容器,子容器寬高不確定。):

  1. 父容器.parent{text-align: center; display: table-cell; vertiacal-align: middle;}。 子容器.child{display: inline-block;}

  2. 利用定位。父容器.parent{position: relative;} 子容器.child{position: absolute; top: 50%, left: 50%; transform: translate(-50%, -50%); }

  3. 利用彈性布局。父容器display: flex; justify-content: center; align-items: center;

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.