居中是 CSS 排版中的常見需求,以下整理了單行、層級、文字等多種居中情境的實用寫法。
文字要在層中垂直居中,vertical-align 屬性是做不到的。這裡有個巧妙做法:讓 height 的高度與 line-height 相同。<div style="line-height:500px;height:500px;"></div>
設 div 寬度小於父 div,再設 margin:0 auto; 即可讓 div 居中:#childdiv {width:200px; margin:0 auto;}
在 childdiv 加上 text-align:center; 即可。
用 display:table-cell 搭配 vertical-align:middle,再透過絕對定位微調:<div style="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></div></div></div>
在方法四的基礎上,外層加上 float:left,內層加上 word-break:break-all 等斷行屬性,即可讓超長英文在居中時自動換行。
加上 overflow-y:scroll 就能讓內容過多時出現垂直捲軸:<div style="width:160px; height:260px; overflow-y:scroll; border:1px solid;">內容</div>
在垂直居中的結構中,最內層加上 text-align:center 或 text-align:left 配合固定寬度,就能靈活控制文字的水平對齊方式。
在垂直居中的最內層用 margin:0 auto; 搭配固定寬度,同樣能實現水平居中,適合需要斷行的長文本場景。
以上八種寫法涵蓋了單行文字、div 層級與長文本等常見居中需求,可依實際情境靈活選用。