在定義網頁 CSS 樣式時,我們未必常會用到垂直居中。本站有大量文章介紹過相關知識。與他人協作時,代碼的自適應性就得做到最好——自己寫頁面時,你或許能保證視覺上是居中的,但萬一這個元素或它的父層被放大了,你還能維持居中嗎?
vertical-align 是個不錯的屬性,但它起初是為表格儲存格而生的。它雖對塊級元素無效,對 span 這類行內元素卻仍然管用(此時設為負值內容下移、正值則上移)。以下整理幾種較專業的居中方案,方便日後查閱。
1. 單行垂直居中
文字在容器中垂直居中,光靠 vertical-align 是做不到的。這裡有個巧妙的做法:讓 height 與 line-height 設為相同值!
<div style="line-height:500px;height:500px;">
2. 層水平居中
將 div 寬度設為小於父層,再設 margin:0 auto;,即可讓它居中。
#parentdiv {width: 500px;}
#childdiv {width: 200px; margin:0 auto;}
3. 層中的文字水平居中
在 childdiv 的 CSS 加上 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:static;position:absolute\9; top: 50%;">
<div style="background:blue;position: relative; top: -50%;">www.poluoluo.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:static;position:absolute\9; 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.poluoluo.com……</div>
</div>
</div>
</div>
</div>
6. div 垂直滾動
<div style="width: 160px; height: 260px; overflow-y: scroll; border: 1px solid;">www.poluoluo.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:static;position:absolute\9;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.poluoluo.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:static;position:absolute\9; 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.poluoluo.com……</div>
</div>
</div>
</div>
</div>