背景:在項目中常常碰到讓元素垂直居中的情形,實現的方法有不少,各有利弊。衆所周知的,用flex佈局很容易就實現,but,一些不是很主流的瀏覽器並不支持flex,這就比較尷尬了,有好東西不能在項目中用起來。今天就利用下業餘時間,彙總一下經常使用的幾種垂直居中的方式。
廢話少說,開整。css
如圖,若是想讓盒子A在盒子B內垂直居中css3
<style> .box { background: gray; height: 100px; width: 200px; } .item { background: pink; height: 20px; width: 100px; } </style> <div class="box"> <div class="item">A</div> </div>
flex方式,兼容到ie10web
.box { display: -webkit-flex; /* 新版本語法: chrome 21+ */ display: flex; /* 新版本語法: opera 12.1, firefox 22+ */ /*flex-direction: row; // 默認水平排列 */ align-items: center; /* 元素排列的垂直方向居中 */ }
利用ifc(行內格式化上下文),其實就是利用行高撐高父元素,視覺上表現也爲垂直居中。chrome
.box { line-height: 100px; } .item { display: inline; }
絕對相對定位瀏覽器
.box { position: relative; } .item { position: absolute; top: 50%; margin-top: -10px; // 自身高度的一半,此用法須要知道自身的高度 // transform: translateY(-50%); // 兼容性容許的話能夠用css3特性代替margin-top } // 絕對定位另外一種方式 .item { position: absolute; top: 0; bottom: 0; margin: auto; // left: 0; right: 0; // 這樣還能水平居中 }
利用vertical-align,爲了避免產生新的dom,可能使用僞類before作輔助,讓子元素與僞類垂直居中對齊dom
.box:before { content: ''; height: 100%; vertical-align: middle; display: inline-block; } .item { display: inline-block; }
忽然發現,實現垂直居中的方法有不少,此處先列舉幾個做參考,若有紕誤,歡迎評論指正。如遇到具體狀況不知道怎麼實現的同窗,也能夠私信我,往後也繼續完善此貼。佈局