行高line-height實(shí)現(xiàn)單行文本垂直居中
以前一直認(rèn)為單行文本垂直居中要將高度和行高設(shè)置成相同的值,但高度其實(shí)沒必要設(shè)置。實(shí)際上,文本本身就在一行中居中顯示。在不設(shè)置高度的情況下,行高撐開高度。
<style> .test{ line-height: 50px; background-color: lightblue; } </style> <div class="test">測試文字</div>
設(shè)置vertical-align:middle實(shí)現(xiàn)垂直居中
【1】設(shè)置父元素的display為table-cell
通過為table-cell元素設(shè)置vertical-align:middle,可使其子元素均實(shí)現(xiàn)垂直居中。這和表格里單元格的垂直居中是類似的
[注意] 若要IE7-瀏覽器支持,則可以將其改為<table>表格結(jié)構(gòu)
[注意] 設(shè)置為table-cell的div不能使用浮動或絕對定位,因?yàn)楦踊蚪^對定位會使元素具有塊級元素特性,從而喪失了table-cell元素具有的垂直對齊的功能。
若需要浮動或絕對定位處理,則需要外面再套一層div。
<style> .parent{ display: table-cell; vertical-align: middle; } </style> <div class="parent" style="background-color: gray;height: 100px;"> <div class="child" style="background-color: lightblue;">我是有點(diǎn)長的有點(diǎn)長的有點(diǎn)長的有點(diǎn)長的測試文字</div> </div>
【2】若子元素是圖片,通過設(shè)置父元素的行高來代替高度,且設(shè)置父元素的font-size為0。
vertical-align:middle的解釋是元素的中垂點(diǎn)與父元素的基線加1/2 父元素中字母X的高度對齊。由于字符X在em框中并不是垂直居中的,且各個字體的字符X的高低位置不一致。
所以,當(dāng)字體大小較大時,這種差異就更明顯。當(dāng) font-size為0時,相當(dāng)于把字符X的字體大小設(shè)置為0,于是可以實(shí)現(xiàn)完全的垂直居中。
<style> .parent{ line-height: 100px; font-size: 0; } .child{ vertical-align: middle; } </style> <div class="parent" style="background-color: lightgray;width:200px;"> <img class="child" src="http://sandbox.runjs.cn/uploads/rs/26/ddzmgynp/img1.gif" width="50%" alt="test"> </div>
【3】通過新增元素來實(shí)現(xiàn)垂直居中的效果
新增元素設(shè)置高度為父級高度,寬度為0,且同樣設(shè)置垂直居中vertical- align:middle的inline-block元素。由于兩個元素之間空白被解析,所以需要在父級設(shè)置font-size:0,在子級再將 font-size設(shè)置為所需值;若結(jié)構(gòu)要求不嚴(yán)格,則可以將兩個元素一行顯示,則不需要設(shè)置font-size:0。
<style> .parent{ height: 100px; font-size: 0; } .child{ display: inline-block; font-size: 20px; vertical-align: middle; } .childSbling{ display: inline-block; height: 100%; vertical-align: middle; } </style> <div class="parent" style="background-color: lightgray; width:200px;"> <div class="child" style="background-color: lightblue;">我是比較長的比較長的多行文字</div> <i class="childSbling"></i> </div>
思路三:通過絕對定位實(shí)現(xiàn)垂直居中
【1】若子元素不定高, 使用top50%配合translateY(-50%)可實(shí)現(xiàn)居中效果。
translate函數(shù)的百分比是相對于自身高度的,所以top:50%配合translateY(-50%)可實(shí)現(xiàn)居中效果。
[注意] IE9-瀏覽器不支持;