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