在定義網頁CSS樣式時,我們或許不太常用到垂直居中。webjx.com上已有大量文章介紹相關知識。在與他人協作時,你的代碼自適應性就需要做到最好——自己寫頁面時也許能保證視覺上是居中的,可一旦這個元素或其父元素變大了,你還能確保它依然居中嗎?
vertical-align是個不錯的屬性,但它最初是針對表格的cell而設計的。這個屬性對塊級元素雖然不起作用,對行內元素(如span)卻仍然有效(此時設為負值元素內容下移,正值則上移)。
下面是幾種比較專業的居中解法,記錄於此以便查閱。
1、單行垂直居中
要讓文字在層中垂直居中,vertical-align屬性是做不到的。這裡有個巧妙的方法:讓height的高度與line-height的高度相同!
<div style="line-height:500px; height:500px;">
2、層水平居中
將div的寬度設為小於父div的寬度,再設定 margin:0 auto;,即可讓div居中。
#parentdiv { width: 500px; }
#childdiv { width: 200px; margin:0 auto; }
3、層中的文字水平居中
在childdiv的CSS加上text-align:center;
#parentdiv { width: 500px; }
#childdiv { width: 200px; margin:0 auto; text-align:center; }
4、div層垂直居中
<div style="width:275px; height:375px; border: solid red;">
<div style="background:green; height:375px; width:275px; position:relative; display:table-cell; vertical-align:middle;">
<div style="background:red; position:absolute; top:50%;">
<div style="background:blue; position:relative; top:-50%;">www.webjx.com</div>
</div>
</div>
</div>
5、div層垂直水平居中,英文超長換行
<div style="float:left; width:275px; height:375px; border: solid red;">
<div style="height:375px; width:275px; position:relative; display:table-cell; vertical-align:middle;">
<div style="position:absolute; top:50%;">
<div style="position:relative; top:-50%; text-align:center;">
<div style="width:85px; WORD-WRAP:break-word; TABLE-LAYOUT:fixed; Word-break:break-all; margin:0 auto;">www.webjx.comwww.webjx.comwww.webjx.com</div>
</div>
</div>
</div>
</div>
6、div垂直滾動
<div style="width:160px; height:260px; overflow-y:scroll; border:1px solid;">
www.webjx.com
</div>
7、垂直居中搭配text-align水平居中
<div style="float:left; width:275px; height:375px; border: solid red;">
<div style="height:375px; width:275px; position:relative; display:table-cell; vertical-align:middle;">
<div style="position:absolute; top:50%;">
<div style="position:relative; top:-50%; text-align:center;">
<div style="width:275px;">
<div style="width:160px; WORD-WRAP:break-word; TABLE-LAYOUT:fixed; Word-break:break-all; text-align:left;">www.webjx.comwww.webjx.comwww.webjx.com</div>
</div>
</div>
</div>
</div>
</div>
8、垂直居中搭配margin水平居中
<div style="float:left; width:275px; height:375px; border: solid red;">
<div style="height:375px; width:275px; position:relative; display:table-cell; vertical-align:middle;">
<div style="position:absolute; top:50%;">
<div style="position:relative; top:-50%;">
<div style="margin:0 auto; width:160px; WORD-WRAP:break-word; TABLE-LAYOUT:fixed; Word-break:break-all;">www.webjx.comwww.webjx.comwww.webjx.com</div>
</div>
</div>
</div>
</div>